Search code examples
javafilefileoutputstream

FileOutput Stream delets text file contents


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class FileIoStream {

    public static void main(String[] args) throws IOException {
        File f = new File("C:\\Users\\rs\\IO\\myfile.txt");
        FileInputStream fis = new FileInputStream(f);
        FileOutputStream fos = new FileOutputStream(f);
    }
}

Every time I make an object for FileOutputStream the contents in myfile.txt get deleted and I do not know why? But when I just new FileInputStream it does not happen.


Solution

  • You should try with this constructor :

    FileOutputStream fos = new FileOutputStream(f, true);
    

    So what you have to add to the file will be appended if it already exists.

    Doc available here