英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论