Question 1. What class would you use to read a few pieces of data that are at known positions near the end of a large file?
Answer 1.RandomAccessFile
.Question 2.In a
format
call, what's the best way to indicate a new line?
Answer 2. Use the%n
conversion — the\n
escape is not platform independent!Question 3. How would you append data to the end of a file? Show the constructor for the class you would use and explain your answer.
Answer 3. Here's a quick answer: Use theFileWriter
andBufferedWriter
classes to append data to the end of the text file. Here is theFileWriter
constructor, you pass intrue
to write to the file in append mode:An alternate answer is to useFileWriter writer = new FileWriter (String filename, boolean append);RandomAccessFile
and skip to the end of the file and start writing:... RandomAccessFile file = new RandomAccessFile(datafile, "rw"); file.skipBytes((int)file.length()); //skip to the end of the file file.writeBytes("Add this text to the end of datafile"); //write at the end of the file file.close(); ...
Exercise 1. Implement a pair of classes, one
Reader
and oneWriter
, that count the number of times a particular character, such ase
, is read or written. The character can be specified when the stream is created. Write a program to test your classes. You can usexanadu.txt
as the input file.
Answer 1. See the following three files:CounterDemo.java
,CountReader.java
, andCountWriter.java
.Exercise 2. The file
datafile
begins with a singlelong
that tells you the offset of a singleint
piece of data within the same file. Using theRandomAccessFile
class, write a program that gets theint
piece of data. What is the
int
data?
Answer 2.123
. SeeFileReader.java
for the solution. If you're interested in seeing how the file was written, seeFileWriter.java
.