Java Reference
In-Depth Information
We will see some other channel read() methods later that we can use to read from a particular
point in the file.
Reading a Text File
We can now attempt to read the very first file that we wrote in the previous chapter - charData.txt .
We wrote this file as Unicode characters so we must take this into account when interpreting the
contents of the file.
We can set up a File object encapsulating the file path to start with and create a FileInputStream object
from that. We can then obtain a reference to the channel that we will use to read the file. We 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, we can only read the file as bytes into a byte buffer. We create that exactly as we saw previously
when we were writing the file. We know that we wrote 48 bytes at a time to the file - we wrote the string
" Garbage in , garbage out\n " that consists of 24 Unicode characters. However, we tried appending to the
file an arbitrary number of times, so we should provide for reading as many Unicode characters as there are.
We can set up the ByteBuffer with exactly the right size with the statement:
ByteBuffer buf = ByteBuffer.allocate(48);
The code that we use to read from the file needs to allow for an arbitrary number of 24-character strings
in the file. Of course, it will also allow for the end-of-file being reached while reading the file. We can
read from the file into the buffer like this:
try {
while(inChannel.read(buf) != -1) {
// Code to extract the data that was read into the buffer...
buf.clear(); // Clear the buffer for the next read
}
System.out.println("EOF reached.");
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
Search WWH ::




Custom Search