3

在 java 中,可能很容易需要做一些事情,例如实例化一个 BufferedWriter 对象。这可以通过以下方式完成:

File outFile = new File("myTestFile.txt");

BufferedWriter w = null;
try { w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")); }
catch (FileNotFoundException|UnsupportedEncodingException e) { System.out.println(e.getMessage()); }

w.write("Test string");
w.newLine();

请注意 w 在 try-catch 块之前声明。这样做是为了在 try-catch 之后使用变量在适当的范围内。它使用空指针初始化,否则像 netbeans 这样的 IDE 会警告该变量可能尚未分配。但是,IDE 仍然抱怨当您到达 w.write() 时,w 可能有一个空值。这很有意义,因为 try 块可能会失败!

有没有一种更优雅、更明智的方法来做到这一点,并且不会导致像我的 IDE 上面提醒我的那样的逻辑问题?

我意识到我可以将 w 所做的一切都包装在 try 块中,但这对我的任务来说是不可行的。如果还有其他选择,我还能如何初始化 w?

谢谢!

4

3 回答 3

2

您只需要包装所有内容,因为这是 Java 语言设计 - 否则(鉴于没有 类似的概念Exceptions),如果您的编写器仍然有效,您将不得不检查对否则抛出异常的操作的每次调用,这甚至更少可行的。

看到 try-catch 块更像是一个特殊的部分,在不完全破坏您的应用程序的情况下可能会发生不良和异常的事情。

于 2014-02-11T15:24:13.000 回答
1

首先,您别无选择,只能将以下几行包装到 try-catch 中:

w.write("Test string");
w.newLine();

因为它们都能够抛出 IOExceptions(不过你也可以声明一个 throws 子句)。

在 Eclipse 中,我没有看到 IDE 抱怨 w 可以为 null 的任何原因,因为您已经明确地初始化了它。

于 2014-02-11T15:25:14.957 回答
1

如果您使用的是 Java 7,请考虑使用try-with-resources 。

try (BufferedWriter w = new BufferedWriter
    (new OutputStreamWriter(
        new FileOutputStream(outFile), "utf-8"))) {
    w.write("Test string");
    w.newLine();
} catch (IOException ex) {
    ex.printStackTrace();
}

如果您的问题是 try 块内的代码量,请考虑将该代码分解为方法。

try (BufferedWriter w = new BufferedWriter
    (new OutputStreamWriter(
        new FileOutputStream(outFile), "utf-8"))) {
    writeEverythingINeed(w);
} catch (IOException ex) {
    ex.printStackTrace();
}

或者,您别无选择,只能将其余语句括在 if 中。

BufferedWriter w = null;
try { w = ... }
catch (FileNotFoundException | UnsupportedEncodingException e) {
    System.out.println(e.getMessage());
}

if (w != null) {
    w.write("Test string");
    w.newLine();
}

同样, if 中的块可以重构为方法。

于 2014-02-11T15:29:15.447 回答