In my program, every time that you run the program, it creates a block of text in a specified text file. The problem is that when it runs, it just overwrites the last block. I tried using Java Tip's code (that he put in a thread titled the same as mine), but I didn't know how to get it to work, as it was surprisingly long.

07-26-2009, 09:39 PM

hardwired

every time that you run the program, it creates a block of text in a specified text file. The problem is that when it runs, it just overwrites the last block.
Some general approaches to this are:
1 — read the file, save the text as you read it, append the new text that you want to write to the file for this session and write all of the text back to the file
2 — use a RandomAccessFile. The javadoc and the tutorial have more about this special class and its use
3 — use a FileWriter which has a constructor with a boolean for appending text. Possible limitation: FileWriter is a convenience class for writing character files.

I tried using Java Tip's code (that he put in a thread titled the same as mine), but I didn't know how to get it to work, as it was surprisingly long.
Java Tip made use of RandomAccessFile in the AppendFileStream class in a clever way. As for the length the class extends the abstract OutputStream class which has 5 methods. The last method (public void write(int b)) is abstract so it must be implemented in/by subclasses. Java Tip implemented 4 of the 5 methods declared in OutputStream (all but the flush method) to direct the writing to the RandomAccesFile.

How to use it is demonstrated in the appendtext class:

Code:

PrintStream out =
new PrintStream(new AppendFileStream("myfile"));
out.print("A new line of text");
out.close();