Reading Data from a File

This chapter discusses Java's FileReader and BufferedReader classes in detail. FileReader and BufferedReader classes are used together when reading data from an external file. The use of the BufferedReader class allows data to be buffered as it is read from a file before manipulating it. The readLine() method of the BufferedReader class reads a line of text from a character-oriented input stream, and puts it into a new String object.

14. C-style Input Loop


Answer:

No. The line terminating characters may be different in the copy. Sometimes this is a useful feature if you often copy text files between different types of computer.

C-style Input Loop

Here is the loop from the copyFile() method.

 line = source.readLine();
  while ( line != null )
  {
   dest.write(line);
   dest.newLine();
   line = source.readLine();
  }


Here is the same loop written in a style that is commonly used with the C programming language. This style also works for Java:

  while ( (line = source.readLine()) != null )
  {
   dest.write(line);
   dest.newLine();
  }


The key to understanding this is to understand that an assignment statement is an expression and has a value. That value is the value that is assigned to the variable. So this:

(line = source.readLine())


has a value that is non-null after a successful readLine() and null upon end-of-file. Say that the file has data in it:

cStyleLoop

This may be more bother than it is worth, but programmers familiar with C are likely to use this style, so you will see it often.


Question 14:

Will this form of the loop work correctly with an empty file?