0
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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Rsp
  • 39
  • 5
  • By the way i do not use any method of this fileout or in classes.i just new them. – Rsp Aug 21 '20 at 13:34
  • The real answer here: read the javadoc of the classes you are using. Seriously, that is the essence of all of programming: you have to understand what you are doing. Dont just use some library class you heard of. Research what it does, and how it does things. Your first stop is always the javadoc of such classes. – GhostCat Aug 21 '20 at 13:47

3 Answers3

1

FileOutputStream by default overwrites the file if it exists. You can use the overloaded constructor to append to that file instead of overwriting it:

FileInputStream fis = new FileInputStream(f, true);
// Here -------------------------------------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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

BenjaminD
  • 488
  • 3
  • 13
1

If gets deleted, because it actually gets overwritten. Every time you create a new FileOutputStream object with new FileOutputStream(File file) constructor, a new FileDescriptor is created, and therefore:

bytes are written to the beginning of the file.

You can think of it, like it starts writing to the file by overwriting everything that previously existed in that file.


You can alternatively create your FileOutputStream object with the FileOutputStream(File f, boolean append) constructor, passing true as a boolean argument into that constructor, and in this case:

bytes will be written to the end of the file rather than the beginning.

You will maintain whatever had been written into the file and your data will be appended to the existing data in the file.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66