Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

java - 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 = 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...