11.3. Reading a Text File

You can now attempt to read the very first file that you wrote in the previous chapter—charData.txt. You wrote this file as Unicode characters, so you must take this into account when interpreting the contents of the file.

Your first step will be to define a File object encapsulating the file path and create a FileInputStream object from that. You can then obtain a reference to the channel from the FileInputStream object that you'll use to read the file. I won't include all the checking here that you should apply to validate the file path, as you know how to do that:

File aFile = new File("C:/Beg Java Stuff/charData.txt");
FileInputStream inFile = null;

try {
  inFile = new FileInputStream(aFile);

} catch(FileNotFoundException e) {
FileChannel inChannel = inFile.getChannel();

Of course, you can only read the data from the file as bytes into a byte buffer. You create a ByteBuffer object exactly as you saw previously when you were writing the file. You know that you wrote 48 bytes at a time to the file—you wrote the string "Garbage in, garbage out\n" that consists of 24 Unicode characters. However, you tried appending to the file an arbitrary number of times, so you should provide for reading as many Unicode characters as there are in the file. You can set up the ByteBuffer with exactly the right size for the data from a single write operation with the following statement:

ByteBuffer buf = ByteBuffer.allocate(48); ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.