Two streams and one file

本秂侑毒 提交于 2019-12-14 03:36:31

问题


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 = is.read();
      os.write(data);
    }
    is.close();
    os.close();

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?


回答1:


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 = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}


来源:https://stackoverflow.com/questions/45537630/two-streams-and-one-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!