首页 > 解决方案 > Java写入文件 - 使用类

问题描述

我在How to append text to an existing file in Java中阅读了与我类似的主题,并在那里尝试了解决方案,不幸的是,他们都没有回答我的具体情况。

我将对文件进行大量更改,因此我认为我将创建方法,该方法将返回PrintWriter对象,我可以通过执行在该对象上进行更改writer.prinln("text");

private static PrintWriter WriteToFile() {

     PrintWriter out = null;
      BufferedWriter bw = null;
      FileWriter fw = null;
      try{
         fw = new FileWriter("smrud.txt", true);
         bw = new BufferedWriter(fw);
         out = new PrintWriter(bw);
//           out.println("the text");
         return out;
      }
      catch( IOException e ){
          return null;
      }
      finally{
         try{
            if( out != null ){
               out.close(); // Will close bw and fw too
            }
            else if( bw != null ){
               bw.close(); // Will close fw too
            }
            else if( fw != null ){
               fw.close();
            }
            else{
               // Oh boy did it fail hard! :3
            }
         }
         catch( IOException e ){
            // Closing the file writers failed for some obscure reason
         }
      }
}

所以在我的主要方法中,我调用了这个方法

PrintWriter writer = WriteToFile();

然后我正在做出改变

 writer.println("the text2");

我正在关闭 writer 以将更改保存到磁盘:

 writer.close();

不幸的是,我没有看到任何变化。当我将更改放入WriteToFile()方法中时,我会看到更改:

private static void WriteToFile() {

     PrintWriter out = null;
      BufferedWriter bw = null;
      FileWriter fw = null;
      try{
         fw = new FileWriter("smrud.txt", true);
         bw = new BufferedWriter(fw);
         out = new PrintWriter(bw);
         out.println("the text");
      }
      catch( IOException e ){
         // File writing/opening failed at some stage.
      }
      finally{
         try{
            if( out != null ){
               out.close(); // Will close bw and fw too
            }
            else if( bw != null ){
               bw.close(); // Will close fw too
            }
            else if( fw != null ){
               fw.close();
            }
            else{
               // Oh boy did it fail hard! :3
            }
         }
         catch( IOException e ){
            // Closing the file writers failed for some obscure reason
         }
      }




}

但是这个方法 open FileWriterBufferedWriter每次PrintWriter它都会被执行,我想通过返回PrintWritermain 方法然后执行writer.println("text");并在一段时间后关闭它来避免这种情况,writer.close();但这不起作用。

任何建议将不胜感激。

标签: java

解决方案


所有的作者都是封闭的,WriteToFile所以当PrintWriter对象被返回时它不会写任何东西。

您将不得不扩大范围PrintWriter并在方法之外对其进行管理WriteToFile

有点像:

public static void main(String[] args) {
    try (PrintWriter printWriter = createWriter()) {
        printWriter.println("Line 1");
        printWriter.println("Line 2");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static PrintWriter createWriter() throws IOException {
    return new PrintWriter(new FileWriter("smrud.txt", true));
}

推荐阅读