Why is this data.txt file deleted whenever I restart the program?
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();
}
}
To add to an existing file instead of overwriting it, use FileOutputStream's constructor that lets you open it in append mode.
fos = new FileOutputStream(data, true);
Because of this line:
fos = new FileOutputStream(data);
This version of the constructor of FileOutputStream will overwite the file, but you could use this version:
public FileOutputStream(File file,
boolean append)
throws FileNotFoundException
You'd have to specify that you want to append to the file by setting the append
field to true
.
You're not appending new information to the file, you're overwriting it.
Anytime you just open it in the
fos = new FileOutputStream(data);
command, it gets emptied, no matter if you have saved anything inside it or not.
Your FileOutputStream
is overwriting your file. If you want to append to the end of the file you need to specify that:
fos = new FileOutputStream(data, true);
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.
精彩评论