Reading and writing to the same file

K so I have a String file which is the path to a file on the computer, its already been checked and everything and it exists, and exceptions are handled and all that junk

all I want to do is read one line at a time from that file, change it, then put it back in at the same spot.

how do i do that? the following isnt working

BufferedReader reader = new BufferedReader(new FileReader(file));

PrintStream out = new PrintStream(new FileOutputStream(file));

while(true){

String line = reader.readline();

line.modify();

out.println(line);

}

thats just an example, I do havea stop condition for the loop and everything.

all it does it empty the file

I don't want to make a new file then change the names around either, this has to be done all in the same .txt file

[838 byte] By [jeanberna] at [2007-11-27 2:39:56]
# 1
- Read in all the lines, adding them to an ArrayList as you go.- Swap the line you want.- Write back all the lines into the file.
CaptainMorgan08a at 2007-7-12 3:02:21 > top of Java-index,Java Essentials,New To Java...
# 2

I want to be doing the lines one by one

your way isnt hard, I had that before, I'm trying to make this program better. Time complexity is less important than space complexity to me, + this is an encryption program so I can't have the original text floating around in a vector or arrayList

jeanberna at 2007-7-12 3:02:21 > top of Java-index,Java Essentials,New To Java...
# 3
RandomAccessFile?
DrLaszloJamfa at 2007-7-12 3:02:21 > top of Java-index,Java Essentials,New To Java...
# 4
> this is an encryption program so > I can't have the original text floating > around in a vector or arrayListWell then remove them from the List as you go.
CaptainMorgan08a at 2007-7-12 3:02:21 > top of Java-index,Java Essentials,New To Java...
# 5
Then you could use RandomAccesFiletoo slow :)Mensaje editado por: Ruly-o_O
Ruly-o_Oa at 2007-7-12 3:02:21 > top of Java-index,Java Essentials,New To Java...
# 6

To read and write to the same file without saving the results in between, you need to use RandomAccessFile or FileChannel. But beware, the amount written, each time, needs to exactly match that read, as there is no "insert"/"delete" function. That makes this solution, essentially, useless, unless the file contains fixed length items.

The only other way, is to read it, and be writing a new file simultaneously, then remove the old and replace it with the new. I'm sorry, but, there is no other way, AFAIK.

masijade.a at 2007-7-12 3:02:22 > top of Java-index,Java Essentials,New To Java...