Help in BufferedOutputStream

Having a little problem with a simple program I'm writing. I want to be able to modify the data of an incoming stream and write the results out to thesame file. However, this does not appear to work as I thought. I assumed if after all the data had been read into the buffer, then I could close the inputStream and therefore flush the buffer to the same file after I closed the outputStream. The file ends up with 0 bytes (was a dummy file anyhow), so what can I do to fix this?

[494 byte] By [Tweaklinga] at [2007-11-26 19:17:54]
# 1

> Having a little problem with a simple program I'm

> writing. I want to be able to modify the data of an

> incoming stream and write the results out to the

> same file. However, this does not appear to

> work as I thought.

No surprise. You have to re-write the entire file.

> I assumed if after all the data

> had been read into the buffer, then I could close the

> inputStream and therefore flush the buffer to the

> same file after I closed the outputStream. The file

> ends up with 0 bytes (was a dummy file anyhow), so

> what can I do to fix this?

I don't understand what you're doing. Can you please post your code?

CeciNEstPasUnProgrammeura at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...
# 2

import java.io.*;

import javax.swing.*;

class NamedClass

{

public static void main(String[] args)

{

JFileChooser picker=new JFileChooser();

BufferedInputStream in;

BufferedOutputStream out;

int returnVal=picker.showOpenDialog(null);

if(returnVal == JFileChooser.APPROVE_OPTION)

{

File chosen= picker.getSelectedFile();

try

{

in=new BufferedInputStream(new FileInputStream(chosen));

out=new BufferedOutputStream(new FileOutputStream(chosen));

int i;

while((i=in.read())!=-1)

{

//Change methods

out.write(i);

}

in.close();

out.close();

}

catch(Exception ex){}

}

}

}

Tweaklinga at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...
# 3
Can anyone suggest a method of executing the program as such so it will write to the same file there after?
Tweaklinga at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...
# 4
1. Write to a new temporary file.2. When done writing, delete the original file and renameTo() to rename thenew file to give it the original name. You must do this in two steps becauserenameTo() is not guaranteed to overwrite an existing file.
DrLaszloJamfa at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...
# 5
That worked perfectly. Thank you.
Tweaklinga at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...
# 6
BTW, That approach is better than the "read entire file, delete, write" approach,because if your program crashes half-way through the write stage of the flawedapproach, you end up with the file being incomplete (corrupted).
DrLaszloJamfa at 2007-7-9 21:32:46 > top of Java-index,Java Essentials,New To Java...