1

我正在编写将异常和有关异常的注释存储在文本文件中的代码。而且我遇到了一个问题,每次调用我的 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 都是静态的。文件声明如下:

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

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

4

2 回答 2

0

尝试移动“真实”:

   toWriter=new FileOutputStream(errReport);
}else{
   toWriter=new FileOutputStream(errReport, true);
于 2013-03-18T19:43:31.553 回答
0

如此链接所示,您应该使用 FileWriter 并将参数作为 true 传递以附加到现有文件。

http://www.xyzws.com/Javafaq/how-to-append-data-to-the-end-of-existing-file-in-java/165

于 2013-03-18T19:42:18.387 回答