FileWriter contains a constructor that takes a file name argument, FileWriter(String), so it can be used with PrintWriter to perform output to a text file:
PrintWriter outStream = // Create output streamnew PrintWriter(new FileWriter(fileName)); // Open file outStream.print (display.getText()); // Display text outStream.close(); // Close output stream
Solution 11.2
An empty file doesn't affect this loop. If the file is empty, it will print a null line. The test line != null, should come right after the readLine(), as it does in the while loop.
Solution 11.3
This loop won't work on an empty text file. In that case, ch would be set to -1, and the attempt to cast it into a char would cause an error.
[Page 553]
Solution 11.4
public void getFileAttributes(String fileName) { File file = new File (fileName); System.out.println(filename); System.out.println("absolute path:" + file.getAbsolutePath()); System.out.println("length:" + file.length()); if (file.isDirectory()) System.out.println("Directory"); else System.out.println("Not a Directory"); } // getFileAttributes()
Solution 11.5
The inStream.close() statement is misplaced in readIntegers(). By placing it inside the same try/catch block as the read loop, it will get skipped and the stream will not be closed. The EOFException should be caught in a separate try/catch block from other exceptions, and it should just cause the read loop to exit.
Solution 11.6
Yes, a binary file containing several SomeObjects would be "readable" by the BinaryIO program because the program will read a String followed by 64 bytes. However, BinaryIO would misinterpret the data, because it will assume that n1 and n2 together comprise a single int, and n3 (64 bits) will be interpreted as a double. A file of SomeObjects could not be read by the ObjectIO program, because SomeObject does not implement the Serializable interface.