C-style Input Loop



Eine gute Antwort könnte sein:

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:

1. Characters are read from the stream, and placed in a new String. The
   readLine() method returns a reference to the String.
                              |
2. The reference is           |
   assigned to line.          |
                  |           |
                --+--   ------+----------
       while ( (line  = source.readLine())   != null )
               -------+-------------------   ---+---
                      |                         |
3. The assignment statement evaluates           |
   to that (non-null) reference.                |
                                                |
4. The != operator compares non-null to null and evaluates to true.
5. The loop body executes.

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.

FRAGE 14:


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