外接程序已存在使用java的文本文件
我正在创建一个java应用程序,其中一些文本将存储在一个文本文件中。但store函数将在一个循环中运行,每个循环都将从其他类获取数据并存储在文本文件中。我希望我的文本文件应该像创建日志一样存储每个周期的数据。下面是一些代码:外接程序已存在使用java的文本文件,java,file,append,printwriter,Java,File,Append,Printwriter,我正在创建一个java应用程序,其中一些文本将存储在一个文本文件中。但store函数将在一个循环中运行,每个循环都将从其他类获取数据并存储在文本文件中。我希望我的文本文件应该像创建日志一样存储每个周期的数据。下面是一些代码: public void store(){ File file = new File("PaperRecord.txt"); try{ PrintWriter fout = new PrintWriter(file);
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或覆盖现有文件时,该代码都会创建新文件paperrecord。我希望同一个文件增加并向下更新(添加更多文本)类是你的朋友亲爱的
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();
}
}
}
}
fout=newprintWriter(newfileoutputstream(file,true))代码>(未测试)注意:捕获异常然后什么也不做几乎总是一个坏主意。请至少调用e.printStackTrace()代码>在上面printStackTrace
被认为是次优的,但它总比没有好得多。要更快地获得更好的帮助,请发布一个或。为此导入什么?java.nio.file.*;确保您使用的是jdk1.7或更高版本。Cheers@TehminaBatool如果这解决了你的问题,请通过投票让我知道答案,谢谢。事实上我已经尝试过了,但是你提供的功能也覆盖了文件appending@TehminaBatool只要用示例工作代码更新我的答案,试着让我知道