文件输出流删除文本文件内容

huangapple go评论73阅读模式
英文:

FileOutput Stream delets text file contents

问题

每次我为FileOutputStream创建一个对象时myfile.txt中的内容都会被删除我不知道为什么
但是当我只创建一个新的FileInputStream时这种情况不会发生
英文:
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.

答案1

得分: 1

FileOutputStream默认情况下会覆盖文件(如果文件存在)。您可以使用重载的构造函数来将内容追加到文件中,而不是覆盖它:

FileInputStream fis = new FileInputStream(f, true);
// 这里 -------------------------------------^
英文:

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 -------------------------------------^

答案2

得分: 1

你应该尝试使用这个构造函数:

FileOutputStream fos = new FileOutputStream(f, true);

这样,如果文件已经存在,你所要添加的内容将会被追加到文件末尾。

可以在这里找到文档。

英文:

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

答案3

得分: 1

如果被删除,是因为它实际上被 覆盖。每次你使用 new FileOutputStream(File file) 构造函数创建一个新的 FileOutputStream 对象时,都会创建一个新的 FileDescriptor,因此:

字节会被写入文件的开头。

你可以把它想象成,它开始写入文件,覆盖了先前存在于文件中的所有内容。


你也可以使用带有 FileOutputStream(File f, boolean append) 构造函数创建 FileOutputStream 对象,将 true 作为布尔参数传递给该构造函数,在这种情况下:

字节将被写入文件的末尾,而不是开头。

你将保留已写入文件的任何内容,你的数据将被附加到文件中已有的数据后面。

英文:

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.

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


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.

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

huangapple
  • 本文由 发表于 2020年8月21日 21:31:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63523856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定