|
Re: Delete/edit/add to a text file or recreate?
|
Posted: Apr 6, 2005 6:53 AM
|
|
Textfiles don't support text editing. It is impossible to change a "line", because "lines" don't exist. They are an abstract concept. A Textfile is a collection of chars with some CR (return) chars in them.
A FileWriter in combination with a BufferedWriter can only append Strings to a file, it can't write specific lines. You can tell the FileWriter to first delete the old file and create a new one or to append to the existing file. A BufferedWriter is not able to change specific bytes inside a file.
Q: Why this limitation? A: Standard Textfiles don't have fixed length lines.
Q: So what's the problem? A: Try to imagine the following scenarios: 1. The new line is shorter then the old one causes: An additional CR char in the line, wich means that you actually add a new line. The original line contains the new content, the inserted line contains the last chars of the old line. The only solution would be again to recreate the whole file after this line. 2. The new line is longer then the old one In this case you overwrite the first chars of the following line. The only solution would be again to recreate the whole file after this line.
It would be very slow to recreate the file everytime you change a line. That's why the standard BufferedWriter does not support writing specific lines.
What you need to do? 1. Open a file reader 2. Read the whole file content in a String[] object or a Vector. 3. close the file reader 3. change the lines wich need to be changed in this String[] object 4. open a filewriter (append = false) write the content of your String[] or Vector into this filewriter 5. close the filewriter.
If you want to use a binary writer instead of the BufferedWriter, make sure your new line allways has the length of the old line or bring all lines to the same length, adding spaces after the line like they do in most database systems.
You started with a too complicated intention (changing lines, ...). First you must understand what a file IS.
Read a file and print it's content to the screen, print out the number of lines you've read, the length of each line. Remove leading and trailing space characters.
Try to play around with only a file writer, create some files, append to an existing file. Try to give all lines the same length.
Only after this experiments try to change a file.
To delete or rename files, use the File.rename() and File.delete() methods. Btw: You can't delete or rename while accessing a file. You must first close all readers and writers.
|
|