我正在创建一个Java应用程序,其中一些文本将存储在文本文件中。但是存储函数将在循环中运行,其中每个循环将从其他类获取数据并存储在文本文件中。我希望我的文本文件应该像创建日志一样在每个周期存储数据。这是一段代码:
public void store(){
File file = new File("PaperRecord.txt");
try{
PrintWriter fout = new PrintWriter(file);
fout.println("Paper Name: " + super.getpSame());
fout.println("Paper Size: " + super.getpSize());
fout.println("Paper Year: " + super.getpYear());
fout.println("Paper Author: " + super.getpAuthor());
fout.println("Paper Description: " + getpDesc());
fout.println("Paper Signature: " + getpSign());
fout.println("Email: " + getPEmail());
fout.println("");
}
catch(FileNotFoundException e){
//do nothing
}
}
从主使用循环调用存储函数:
while(!q.isEmpty()){
Papers temp = q.remove();
temp.print();
temp.store();
}
目前使用此代码的问题是代码每次都会创建新文件paperrecord或覆盖现有代码。我希望向下增加和更新相同的文件(添加更多文本)
答案 0 :(得分:0)
Files上课是你的朋友。
try {
Files.write(Paths.get("PaperRecord.txt"), "new text appended".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
或者,示例工作代码:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample {
private static final String FILENAME = "E:\\test\\PaperRecord.txt";
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String data = " This is new content";
File file = new File(FILENAME);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}