[英]How do I edit the end of a text File in java Across multiple instances of a class
我正在编写将异常和有关异常的注释存储在文本文件中的代码。 而且我遇到一个问题,每次我调用StoreErrors类的新实例时,都会重写Error文件,而不是将数据写入文件末尾。
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都是静态的。 文件声明如下:
私有静态文件errReport = new File(“ err_Report.txt”);
另外,在实际使用编写器写入文件时,我还使用了toLog.write(“ string” +“ \\ r \\ n”)而不是追加。 问题是我每次调用该类时如何使它附加到同一文件的末尾,为什么用当前代码覆盖该文件?
如该链接所示,您应该使用FileWriter并将参数true传递给现有文件。
http://www.xyzws.com/Javafaq/how-to-append-data-to-the-end-of-existing-file-in-java/165
尝试移动“ true”:
toWriter=new FileOutputStream(errReport);
}else{
toWriter=new FileOutputStream(errReport, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.