Java FileWriter问题-必须捕获未报告的IOEXception

Java FileWriter问题-必须捕获未报告的IOEXception,java,exception,java-io,filewriter,Java,Exception,Java Io,Filewriter,我在尝试使用FileWriter写入文件时遇到了Java中的一个问题。只需声明FileWriter writer=newfilewriter(“filelocation”)生成必须捕获的未报告IOException 为了纠正这一点,我自然会将FileWriter放在try-catch块中,但这会导致范围问题。为了解决这个问题,我尝试在try-catch块之前声明FileWriter,并在try-catch中分配位置。在try-catch块之后,当我想使用FileWriter时,它告诉我它可能尚未

我在尝试使用FileWriter写入文件时遇到了Java中的一个问题。只需声明
FileWriter writer=newfilewriter(“filelocation”)生成必须捕获的未报告IOException

为了纠正这一点,我自然会将FileWriter放在try-catch块中,但这会导致范围问题。为了解决这个问题,我尝试在try-catch块之前声明FileWriter,并在try-catch中分配位置。在try-catch块之后,当我想使用FileWriter时,它告诉我它可能尚未初始化。我不确定如何处理这个问题,也从未在Java1.7或类似版本中遇到过这个问题

这是一个在我不清楚的情况下我最终处境的例子

Scanner userInput = new Scanner(System.in);
FileWriter writer;
try {
    System.out.println("Enter the file directory you would like to store in");
    String fileLocation = userInput.nextLine();
    writer = new FileWriter(fileLocation);
} catch(java.io.IOException e) {
    System.out.println("Error message");
}
writer.write("Stuff"); //writer may not have been initialized
好办法是:

System.console().printf("Enter the file directory you would like to store in");
String location = System.console().readLine();
try (FileWriter writer = new FileWriter (location)) {
  writer.write("Stuff");
} catch (IOException e) {
  new RuntimeException("Error message", e).printStackTrace();
}
说明:

  • System.console().printf()
    启用在上打印消息<代码>系统输出
  • 可能更可取,因为不严格要求有“控制台”
  • 使用
    System.console()
    进行控制台管理。更容易、更清楚。不要忘记分配控制台(即不要使用
    javaw
    executable)
  • 使用打开流
  • printStackTrace()
    print可轻松找到代码中的错误位置
  • 我构建了一个新的异常,将错误消息附加到堆栈跟踪中,并在堆栈中添加“catch”位置
  • 忠告:

  • 使用字节流进行文件访问(ie)。它支持强制执行字符集(ie)和缓冲(ie或)
  • 使用字节流还可以切换到
  • 用于访问默认(且大部分常用)字符集(所有JVM实现都必须支持的字符集)
  • 阅读
  • 调用
    printStackTrace()
    不是很好,您应该快速引入日志系统来打印消息
  • 如果出现问题,在使用日志记录系统时要注意不要混淆用户对系统交互(即提示用户输入)和反馈(即进度消息)的看法
  • 你说“自然”,你把它放在一个试抓块内。这并不自然,因为有两种处理方法,另一种更常见:

    • 在try-catch块中处理异常
    • 不处理异常,但声明您的方法抛出异常,并允许它级联调用堆栈
    您的代码看起来像是在
    main
    方法中,因此您可以添加
    抛出IOException

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

    但是,在您的特定情况下,您是从用户提示中获取文件位置的,因此,与其让程序因错误而死掉,不如告诉用户错误并提示输入新名称

    此外,请记住关闭您的资源

    public static void main(String[] args) throws IOException {
        Scanner userInput = new Scanner(System.in);
        FileWriter writer;
        do {
            System.out.println("Enter the file name you would like to store in");
            String fileLocation = userInput.nextLine();
            if (fileLocation.trim().isEmpty())
                return; // Exit program when user pressed enter with a name
            try {
                writer = new FileWriter(fileLocation);
            } catch(java.io.IOException e) {
                System.out.println("Cannot write to file: " + e);
                writer = null;
            }
        } while (writer == null);
        try {
            writer.write("Stuff"); //writer may not have been initialized
        } finally {
            writer.close();
        }
    }
    

    写入
    关闭
    在技术上仍然会抛出错误(例如磁盘已满),我们允许该错误级联并终止程序。

    这是预期行为。您需要执行
    writer。在构造函数调用下的try块中写入
    。问题是在我的实际代码中,在我使用writer之前还有大约90行代码。我认为把所有的东西都放在试块里是不好的做法。在这方面我错了吗?另一方面,这似乎是一种奇怪的有意行为。如果在try-catch中初始化FileWriter时出错,它将在抛出错误时退出该方法,因此永远不会调用writer.write。我对1.8的看法完全不同了!杰森:它在try块中的语义是正确的。不过,更合适的是a。好吧,我来看看。我应该能够按照你告诉我的把它整理好,所以非常感谢你!Java
    FileWriter
    自1997年以来抛出了
    IOExceptions
    。这不是“Java1.8的问题”。因为OP显然不关心编码,所以使用
    FileWriter
    是更好的选择。现在不要把代码复杂化,因为有些东西你可能永远都不需要。如果需要更改,您可以随时在以后重构捕获异常并打印堆栈跟踪,然后让代码继续,这会导致灾难。除非您已经处理了异常,否则您很少希望执行以下代码。为什么您认为使用
    System.console()
    打印消息比使用
    System.out
    更好?特别是当您不以这种方式打印堆栈跟踪时?为什么要创建一个新的
    RuntimeException
    (创建一个全新的附加但无用的堆栈跟踪),只是为了打印抛出的
    IOException
    ?您应该意识到
    System.console()
    可以根据所使用的IDE返回
    null
    。坚持使用
    System.out
    在控制台上打印,避免使用易发生异常的代码。@Andreas我看到过太多缺乏编码/字符集管理的情况,所以不能教育傻瓜(而不是借口)。提到