Two streams and one file

What will happen if I create two instances of class FileInputStream and FileOutputStream using the default constructor and as an argument specify the same path and file name like this..

 FileInputStream is = new FileInputStream("SomePath/file.txt");  
 FileOutputStream os = new FileOutputStream("SamePath/file.txt");

Let’s imagine that we have a few strings inside the file “file.txt”. Next, using a loop I am trying to read bytes from the file.txt and write them into the same file.txt each iteration, like this:

 while (is.available()>0){
      int data =;

The problem is that when I am trying to run my code, all text from the file.txt just erasing. What happens when two or more streams trying to work with the same file? How does Java or the file system work with such a situation?

It depends on your operating system. On Windows the new FileOutputStream(…) will probably fail. On Unix-line systems you will get a new file while the old one continues to be readable.

However your copy loop is invalid. available() is not a test for end of stream, and it’s not much use for other purposes either. You should use something like this:

byte[] buffer = new byte[8192];
int count;
while ((count = > 0)
    out.write(buffer, 0, count);