Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中跨类的多个实例编辑文本文件的结尾_Java - Fatal编程技术网

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

如何在java中跨类的多个实例编辑文本文件的结尾,java,Java,我正在编写代码,将异常和有关异常的注释存储在文本文件中。 我遇到了一个问题,每次调用StoreErrors类的新实例时,错误文件都会被重写,而不是将数据写入文件末尾 public StoreErrors(Exception e){ //increment the error number as the number of times StoreErrors //was intialized errorNum +=1; try{

我正在编写代码,将异常和有关异常的注释存储在文本文件中。 我遇到了一个问题,每次调用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=新文件(“err_Report.txt”)

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

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

尝试移动“true”:

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

太棒了,谢谢你。我知道这一定很简单。只是想不出是什么。