【问题标题】:Using PrintWriter to print an array使用 PrintWriter 打印数组
【发布时间】:2023-03-10 16:27:01
【问题描述】:

我有一个名为 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();
    }
}

非常感谢您对此事的任何帮助!

【问题讨论】:

  • 你了解检查异常吗?阅读docs.oracle.com/javase/tutorial/essential/exceptions 另请注意,您应该使用 try-with-resources 语句或 try/finally 语句在最后关闭您的编写器 - 而 not 在循环内。
  • @JonSkeet 我现在将阅读这些内容,谢谢。

标签: java arrays printstream


【解决方案1】:

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

  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();
}

    }

正如 Jon Skeet 所提到的

【讨论】:

  • 是的,它也可以正常运行,但是你说的很好。谢谢,我已经修改了我的答案。
  • 我绝不会建议像那样使用catch (Exception)...我们不知道 OP 是否应该真正声明他们的方法可以抛出 IOException...并且至少 它应该只捕获 IOException。 (我也不会使用 FileWriter 或 PrintWriter,但是...)
  • @Jon Skeet,它通常是我用来处理大部分异常的,但我真的忘了提到 PrintWriter 类的 IOException 异常。
  • 你的意思是你经常赶上Exception?咳!
  • @Jon Skeet,是的,我不记得大多数异常是由语句引发的,所以从 IDE(Eclipse) 获得帮助,或者我一般使用异常。
【解决方案2】:

这里的其他答案有一些缺陷,如果您使用的是 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
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多