如何在if语句中使用Try-with-resources? [英] How to use Try-with-resources with if statement?
本文介绍了如何在if语句中使用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
.
It is allows me to reuse FileReader
. Is it possible? If not, how to correctly reuse FileReader
? I use java 8
, if it is important.
推荐答案
您始终必须定义try-with-resources块的新变量部分. 这是Java 7/8中当前实现的局限性.在Java 9中,他们考虑支持您的本地需求.
You always have to define a new variable part of try-with-resources block. It is the current limitation of the implementation in Java 7/8. In Java 9 they consider supporting what you asked for natively.
不过,您可以使用以下小技巧:
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) {
////
}
}
}
这篇关于如何在if语句中使用Try-with-resources?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文