gpt4 book ai didi

java - 如何在java中跨类的多个实例编辑文本文件的结尾

转载 作者:行者123 更新时间:2023-12-01 04:48:04 24 4
gpt4 key购买 nike

我正在编写代码,将异常和有关异常的注释存储在文本文件中。我遇到了一个问题,每次调用 StoreErrors 类的新实例时,错误文件都会被重写,而不是将数据写入文件末尾。

public StoreErrors(Exception e){
//increment the error number as the number of times StoreErrors
//was intialized
errorNum +=1;
try{
FileOutputStream toWriter;
if(!errReport.exists()){
boolean isCreated =errReport.createNewFile();
if(isCreated){
System.out.println("No Error Report was found a new one "
+ "has been created");
}
/*if the file is already present set append to file to true on
* FileOutputStream
*/
toWriter=new FileOutputStream(errReport, true);
}else{
toWriter=new FileOutputStream(errReport);
}
//OutputStreamWriter allows toLog to be writen in UTF8
//BufferedWriter Takes characters from the OutputStreamWriter
/*Which Writes to the file using the File errReport using
* FileOutputStream toWriter
*/
toLog=new BufferedWriter(new OutputStreamWriter(
toWriter, "UTF8"));
/*Creates and exception object which can be used to get information
* about the error that occured
*/
storeException=e;
}catch (UnsupportedEncodingException encEx){
encEx.printStackTrace();
}catch(IOException ioEx){
ioEx.printStackTrace();
}catch (Exception ex){
ex.printStackTrace();
}
}

这是每次存储新错误时调用的构造函数。请告诉我使用 BufferedReader(OutputStreamWriter(FileOutputStream(File, append boolean), Encoding)) 的组合是否正确。errorNum 和 errReport 都是静态的。文件声明如下:

私有(private)静态文件 errReport=new File("err_Report.txt");

此外,在实际使用编写器写入文件时,我使用 toLog.write("string"+"\r\n") 而不是追加。问题是如何做到这样,每次调用该类时,它都会附加同一文件的末尾,为什么它会用当前代码覆盖该文件?

最佳答案

尝试移动“true”:

   toWriter=new FileOutputStream(errReport);
}else{
toWriter=new FileOutputStream(errReport, true);

关于java - 如何在java中跨类的多个实例编辑文本文件的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com