为什么每当我重新启动程序时,这个 data.txt 文件就会被删除?
我有一个简单的 txt 文件,只能保存 1 个单词,但是每当我重新启动程序时,data.txt 中的所有内容都会被删除 - 我不知道为什么?
全类代码:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class InfoSaver {
File data = new File("data.txt");
FileOutputStream fos;
PrintStream writer;
FileInputStream fis;
DataInputStream reader;
public void init() throws IOException{
fos = new FileOutputStream(data);
writer = new PrintStream(fos);
fis = new FileInputStream(data);
reader = new DataInputStream(fis);
}
public void writeData(String info) {
writer.println(info);
}
public String readData() throws IOException{
return reader.readLine();
}
public void close() throws IOException{
writer.close();
reader.close();
}
}
I have a simple txt file that will save only 1 word, but whenever I restart the program everything inside the data.txt is deleted - I don't know why?
The whole class code:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class InfoSaver {
File data = new File("data.txt");
FileOutputStream fos;
PrintStream writer;
FileInputStream fis;
DataInputStream reader;
public void init() throws IOException{
fos = new FileOutputStream(data);
writer = new PrintStream(fos);
fis = new FileInputStream(data);
reader = new DataInputStream(fis);
}
public void writeData(String info) {
writer.println(info);
}
public String readData() throws IOException{
return reader.readLine();
}
public void close() throws IOException{
writer.close();
reader.close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要添加到现有文件而不是覆盖它,请使用 FileOutputStream 的构造函数,该构造函数允许您以附加模式打开它。
To add to an existing file instead of overwriting it, use FileOutputStream's constructor that lets you open it in append mode.
由于这一行:
此版本的 FileOutputStream 构造函数 将覆盖文件,但您可以使用 此版本:
您必须通过将
append
字段设置为true
来指定要附加到文件。Because of this line:
This version of the constructor of FileOutputStream will overwite the file, but you could use this version:
You'd have to specify that you want to append to the file by setting the
append
field totrue
.您不是在文件中附加新信息,而是覆盖它。
任何时候你只要在
命令,它会被清空,无论您是否在其中保存了任何内容。
You're not appending new information to the file, you're overwriting it.
Anytime you just open it in the
command, it gets emptied, no matter if you have saved anything inside it or not.
您的
FileOutputStream
正在覆盖您的文件。如果您想附加到文件末尾,您需要指定:当您遇到意外行为时,最好检查 API 以确保您调用的函数正在执行您期望的操作。 以下是
FileOutputStream
构造函数的 API。Your
FileOutputStream
is overwriting your file. If you want to append to the end of the file you need to specify that:When you encounter unexpected behavior it's a good idea to check the API to ensure the functions you're calling are doing what you expect. Here is the API for the
FileOutputStream
constructor.