[JAVA] try-with-resources is convenient

Automatically close resources

It's like opening a file, trying-catch it, and closing it. I think I'll do it well When you try to use finally

long.java


	// try
		//Open file
	
	// catch
		//Exception handling
	
	// finally
		//Close file
	
	public static void main(String[] args) {
		
		String filePath = "C:\\Windows\\System32";
		BufferedReader bufferedReader = null;
		
		try {
			//Open file
			File file = new File(filePath);
			
			//Read
			FileReader fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			
			//output
			String data;
			while ((data = bufferedReader.readLine()) != null) {
				System.out.println(data);
			}
			
		} catch (IOException e) {
			System.out.println("Hiraken");
			
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					System.out.println("Tojiren");
				}
			}
		}
	}

If you use the try-with-resource statement, you can do this ...

Smart.java


	// try
		//Open the file, close it without permission
	
	// catch
		//Exception handling
	
	public static void main(String[] args) {
		
		String filePath = "C:\\Windows\\System32";
		
		try (FileReader fileReader = new FileReader(new File(filePath));
				BufferedReader bufferedReader = new BufferedReader(fileReader);) {
			
			//output
			String data;
			while ((data = bufferedReader.readLine()) != null) {
				System.out.println(data);
			}
			
		} catch (IOException e) {
			System.out.println("Hiraken");
		}
	}

Variables declared inside the parentheses () after try It will be closed without permission (java.lang.AutoCloseable)

With the scope up to the inside of the try clause, the usability is the same as declaring it in the try clause.

It ’s too clever and too convenient to close it without permission.

Recommended Posts

try-with-resources is convenient
JUnit 5 parameterization test is super convenient
ActiveModel is convenient when creating Form class
10⁹⁹⁴²⁰⁶⁷ is 8 digits