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

时间:2013-03-18 19:37:19

标签: java

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

private static File errReport = new File(“err_Report.txt”);

当我实际使用writer写入文件时,我也使用了log.write(“string”+“\ r \ n”)而不是追加。 问题是我怎样才能这样做,每当我调用类时它会附加同一个文件的结尾,为什么用当前代码覆盖文件呢?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

尝试移动'true':

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