0

我有一个名为 theDirectory 的数组,它包含许多 DirectoryEntry,每个都由一个名称和 telno 组成。我现在需要将目录中的每个目录条目打印到一个文本文件中。这是我尝试过的方法,但是我收到错误:未报告的异常IOException;必须被抓住或宣布被扔掉。

我的代码:

public void save() {
    PrintWriter pw = new PrintWriter(new FileWriter("directory.txt", true)); 

    for (DirectoryEntry x : theDirectory) {
        pw.write(x.getName());
        pw.write(x.getNumber());
        pw.close();
    }
}

对此问题的任何帮助将不胜感激!

4

2 回答 2

0

您修改后的代码应如下所示:

  public void save() {

PrintWriter pw=null;
    try{
        pw = new PrintWriter(new FileWriter("directory.txt", true)); 

        for (DirectoryEntry x : theDirectory) {
            pw.write(x.getName());
            pw.write(x.getNumber());

        }

    }
    catch(IOException e)
    {
     e.printStackTrace();
    }

finally
{
   pw.close();
}

    }

正如乔恩斯基特所说

于 2014-04-10T19:26:14.107 回答
0

这里的其他答案有一些缺陷,如果您使用的是 Java 7 或更高版本,这可能是您想要的:

public void save() {
    try (PrintWriter pw = new PrintWriter(new FileWriter("directory.txt", true))) {         
        for (DirectoryEntry x : theDirectory) {
            pw.write(x.getName());
            pw.write(x.getNumber());                
        }
    }
    catch (IOException ex)
    {
        // handle the exception
    }   
}
于 2014-04-10T19:32:28.377 回答