1

我是一个中等经验的 C++ 人,正在慢慢学习 Java。我正在编写一个需要执行以下操作的程序:

  • 创建一个简单的文本文件,默认目录就可以了
  • 在程序运行时,定期将一行数据写入文件。根据许多因素,程序可能会写入文件一次或一百万次。没有办法知道哪个写入将是最后一个。

我一直在研究不同的方法来做到这一点,这是我想出的工作代码。有两个文件,“PeteProgram.java”和“PeteFileMgr.java”:

/*
"PeteProgram.java"
*/

import java.io.*;
import java.lang.String;

public class PeteProgram {

    public static void main(String[] args) throws IOException {

      String PeteFilename="MyRecordsFile.txt";
      Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
      PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);

      MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
      MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
      MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");

    }
}


//=====================================================================================================
//=====================================================================================================


/*
"PeteFileMgr.java"
*/

import java.io.*;

public class PeteFileMgr {

  public PeteFileMgr(Writer writer) {

       try {
          writer.write("File created!");

             } catch (IOException ex) {
          // report
          } finally {
             try {writer.close();} catch (Exception ex) {}
          }
      }

  void AddThisString(Writer writer, String AddThis) {

    try {
          writer.append(AddThis);

             } catch (IOException ex) {
          // report
          } finally {
             try {writer.close();} catch (Exception ex) {}
          }
      } 
  }   

文件的初始创建工作得很好。但是,要添加的行不会写入文件中。因为程序编译和运行没有错误,我假设程序尝试编写添加的行,失败并抛出异常。(不幸的是,我正在使用原始编译器/调试器,无法查看是否是这种情况。)

有人发现我的错误吗?

       Many thanks!
            -P
4

1 回答 1

3

那是因为你没有冲洗Writer. 你应该flush不时打电话。此外,你应该在closeWriter 的应用程序的末尾,而不是在将内容写入其中之后。close方法自动刷新作者的内容。

所以,这就是你的代码应该是这样的:

public class PeteProgram {
    public static void main(String[] args) {
        String peteFilename = "MyRecordsFile.txt";
        //here's when the physical file is created
        Writer writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"));
        PeteFileMgr peteFileMgr = new PeteFileMgr(writer);

        peteFileMgr.addThisString(writer, "Add this line #1\n");
        peteFileMgr.addThisString(writer, "Add this line #2\n");
        peteFileMgr.addThisString(writer, "Add this line #3\n");
        } catch (IOException e) {
            //handle the exception
            //basic handling
            e.printStacktrace();
        } finally {
            //this is a must!
            try { writer.close(); } catch(IOException silent) { }
        }
    }
}

public class PeteFileMgr {
    public PeteFileMgr(Writer writer) {
        try {
            //this method is not creating the physical file
            writer.write("File created!");
        } catch (IOException ex) {
          // report
        } finally {
            //remove this call to close
            //try {writer.close();} catch (Exception ex) {}
        }
    }

    public void addThisString(Writer writer, String addThis) {
        try {
            writer.append(addThis);
        } catch (IOException ex) {
            // report
        } finally {
            //remove this call to close
            //try {writer.close();} catch (Exception ex) {}
        }
    }
}

或者,如果使用 Java 7 或更高版本,请使用try-with-resources

public class PeteProgram {
    public static void main(String[] args) {
        String peteFilename = "MyRecordsFile.txt";
        //here's when the physical file is created
        try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"))) {
        PeteFileMgr peteFileMgr = new PeteFileMgr(writer);

        peteFileMgr.addThisString(writer, "Add this line #1\n");
        peteFileMgr.addThisString(writer, "Add this line #2\n");
        peteFileMgr.addThisString(writer, "Add this line #3\n");
        } catch (IOException e) {
            //handle the exception
            //basic handling
            e.printStacktrace();
        }
    }
}
于 2014-11-20T19:40:04.240 回答