O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) {
  e.printStackTrace(System.err);
  System.exit(1);
}
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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required