java - 如何在 if 语句中使用 try-with-resources?

标签 java resources java-7 try-with-resources

我有简单的代码:

try (FileReader file = new FileReader(messageFilePath);
     BufferedReader reader = new BufferedReader(file)) {

    String line;
    while ((line = reader.readLine()) != null) {
        ////
    }
} 

我想写这样的东西:

FileReader file = null;
///.....

try (file = (file == null ? new FileReader(messageFilePath) : file);
     BufferedReader reader = new BufferedReader(file)) {

    String line;
    while ((line = reader.readLine()) != null) {
        ////
    }
} 

它将允许我重用 FileReader。是否可以?如果不是,如何正确重用 FileReader

附言
如果它很重要,我会使用 Java 8。

最佳答案

您总是必须定义 try-with-resources block 的新变量部分。 这是 Java 7/8 中实现的当前限制。在 Java 9 中,他们考虑支持您 native 要求的内容。

但是您可以使用以下小技巧:

public static void main(String[] args) throws IOException {
    FileReader file = null;
    String messageFilePath = "";

    try (FileReader reader = file = (file == null ? new FileReader(messageFilePath) : file);
            BufferedReader bufReader = new BufferedReader(file)) {

        String line;

        while ((line = bufReader.readLine()) != null) {
            ////
        }
    }
}

关于java - 如何在 if 语句中使用 try-with-resources?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702219/

相关文章:

spring - 多模块 GWT 2.4.0 - Spring 3.1.1 应用程序中的静态资源

java - Arrays.sort(比较器)- Java 6 与 Java 7

java - 如何在 Java 中将字符串 AM/PM 日期转换为时间戳?

java - 如果未使用 Swing 事件,如何返回该事件?

java - 缺少内存 : size of young generation includes only one survivor space

java - Hibernate无法解析连接字符串

android - Android中,字符串值和图形资源如何随主题切换?

Java HashMap 覆盖以前的值

asp.net - 使用 HTTP 处理程序中的 ASP.NET 资源文件

java - 将 hibernate 从 3.2.4.sp1 升级到合适的版本