简体   繁体   English

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

[英]How to use try-with-resources with if statement?

I have the simple code:我有简单的代码:

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

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

I want to write something like this:我想写这样的东西:

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

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

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

It would allow me to reuse FileReader .它将允许我重用FileReader Is it possible?是否可以? If not, how to correctly reuse FileReader ?如果没有,如何正确重用FileReader

PS聚苯乙烯
I use Java 8, if it is important.我使用 Java 8,如果它很重要的话。

You always have to define a new variable part of try-with-resources block.您始终必须定义 try-with-resources 块的新变量部分。 It is the current limitation of the implementation in Java 7/8 .这是 Java 7/8 中实现的当前限制 In Java 9 they consider supporting what you asked for natively.在 Java 9 中,他们考虑支持您本机要求的内容。

You can however use the following small trick:但是,您可以使用以下小技巧:

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) {
            ////
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM