Resource를 사용하고 난 이후 반납하기 위함.
try-catch-finally를 사용한 코드
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TryCatchFinally{
public static void main(String[] args){
try {
// Scanner 리소스 try 구문 내에서 생성
Scanner scanner = new Scanner(new File("file.txt"));
System.out.println(scanner.nextLine());
} catch(FileNotFoundException e) {
e.printStackTrace();
} finally {
// Scanner 리소스 finally에서 반납하기.
if(scanner!=null){
scanner.close();
}
}
}
}
try-with-resources를 사용한 코드
import java.io.File;
import java.io.File.NotFoundException;
import java.util.Scanner;
public class TryWithResources{
public static void main(String[] args){
// try 구문 옆에 () 괄호에 Resources 생성하면, 자동으로 반납된다.
try(Scanner scanner = new Scanner(new File("file.txt"))){
System.out.println(scanner.nextLine());
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
try-with-resources 구문에 사용되는 리소스는 java.lang.AutoCloseable 인터페이스를 구현해야한다.
import java.lang.AutoCloseable;
public class Resourecs implements AutoCloseable {
public Resources() {
System.out.println("Resources 생성자");
}
@Override
public void close() throws Exception {
System.out.println("Resourecs close")
}
}
import java.io.File;
import java.io.File.NotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class TryWithResources{
public static void main(String[] args){
// try 구문 옆에 () 괄호에 Resources 생성하면, 자동으로 반납된다.
try(Scanner scanner = new Scanner(new File("file1.txt"));
PrintWriter printwriter = new PrintWriter(new File("file2.txt"))){
System.out.println(scanner.nextLine());
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}