Use Reader.read(). A return value of -1 means end of stream; else, cast to char.
This code reads character data from a list of file arguments:
public class CharacterHandler {
public static void main(String[] args) {
// replace this with a known charset if possible
Charset charset = Charset.defaultCharset();
try {
for (String filename : args) {
File file = new File(filename);
parseFile(file, charset);
}
} catch (Exception e) {
System.err.println("Error");
e.printStackTrace();
}
}
private static void parseFile(File file, Charset charset)
throws IOException {
InputStream in = new FileInputStream(file);
try {
Reader reader = new InputStreamReader(in, charset);
// buffer input because you're reading one char at a time
Reader buffer = new BufferedReader(reader);
handleCharacters(buffer);
} finally {
in.close();
}
}
private static void handleCharacters(Reader reader)
throws IOException {
int r;
while ((r = reader.read()) != -1) {
char ch = (char) r;
System.out.println("Do something with " + ch);
}
}
}
The bad thing about the above code is that it uses the system's default character set. Wherever possible, prefer a known encoding (ideally, a Unicode encoding if you have a choice). See the Charset class for more. (If you feel masochistic, you can read this guide to character encoding.)
(One thing you might want to look out for are supplementary Unicode characters - those that require two char values to store. See the Character class for more details; this is an edge case that probably won't apply to homework.)