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]

> 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?
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){}
}
}
}
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).