两流一文件 [英] Two streams and one file

查看:256
本文介绍了两流一文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用默认构造函数创建类FileInputStream和FileOutputStream的两个实例,并以此作为参数指定相同的路径和文件名,将会发生什么.

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

假设我们在文件"file.txt"中有一些字符串.接下来,使用循环,我尝试从file.txt中读取字节,并在每次迭代中将它们写入相同的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();

问题在于,当我尝试运行代码时,file.txt中的所有文本都将被擦除.当两个或多个流尝试使用同一文件时会发生什么? Java或文件系统在这种情况下如何工作?

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?

推荐答案

这取决于您的操作系统.在Windows上,new FileOutputStream(...)可能会失败.在Unix-line系统上,您将获得一个新文件,而旧文件仍可被读取.

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.

但是,您的复制循环无效. available()并不是流结束的测试,也没有用于其他目的的用途.您应该使用这样的内容:

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

这篇关于两流一文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆