在IntelliJ IDEA中,如何使用try-with-resources包围代码块?

16
在IntelliJ IDEA中,我可以按下"Surround with"快捷键CTRL-ALT-T,将代码块包围在try / catch块等内容中。我想将资源部分包围在try-with-resources块中。
Writer out = Files.newBufferedWriter(destination, StandardCharsets.UTF_8);
temp.process(model, out);

变成这样:

try (Writer out = Files.newBufferedWriter(destination, StandardCharsets.UTF_8)) {
    temp.process(model, out);
}

然而,当按下CTRL-ALT-T时,此选项不可用。

我如何将代码块用try-with-resources块包围?

2个回答

21

按下表示AutoCloseable的任何表达式上的ALT-ENTER

"使用try-with-resources块包围"是一种意图操作。它不是"环绕"菜单中可用的选项。

try with resources screenshot


如果这是一个链式方法调用,我发现我必须先将AutoCloseable提取到它自己的变量中。具体来说,我正在处理java.util.stream.Stream值,尽管我猜想这通常是正确的。 - M. Justin
请问,“Intention action”是什么意思,为什么我不能在菜单中使用它?如何添加它? - KaderLAB

1
在你的语句末尾添加.twr

enter image description here

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接