Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In IntelliJ IDEA, how to surround with try-with-resources?

In IntelliJ IDEA, I can press the "Surround with" shortcut CTRL-ALT-T to surround a block of code with a try / catch block, among other things.

I would like to surround the resource part into a try-with-resources block:

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

To this:

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

However, this option is not available when pressing CTRL-ALT-T.

How can I surround a block of code with a try-with-resources block?

like image 344
Hay Avatar asked Oct 04 '16 21:10

Hay


People also ask

How do I surround the code with if for try catch in IntelliJ?

Simply select the code block to surround (don't forget to use Ctrl + W to increase the current selection) and then press Ctrl + Alt + T (or right-click the selection and select Surround with… from the menu). IntelliJ IDEA will show a list of options to choose from.

How do I search for resources in IntelliJ?

From the main menu, select Edit | Find | Find in Files Ctrl+Shift+F . In the search field, type your search string. Alternatively, in the editor, highlight the string you want to find and press Ctrl+Shift+F . IntelliJ IDEA places the highlighted string into the search field.

How do I navigate through methods in IntelliJ?

To navigate backwards, press Ctrl+Alt+Left . To navigate forward, press Ctrl+Alt+Right . To navigate to the last edited location, press Ctrl+Shift+Backspace . To find the current caret location in the editor, press Ctrl+M .


1 Answers

Press ALT-ENTER on any expression representing an AutoCloseable.

"Surround with try-with-resources block" is an Intention action. It is not an option available in the "Surround with" menu.

try with resources screenshot

like image 121
Hay Avatar answered Sep 18 '22 18:09

Hay