package item09_tryResource;
import java.io.*;
public class compareTrys {
public static void main(String[] args) throws IOException {
System.out.println(firstLineOfFile("test.txt"));
copy("test.txt", "test2.txt");
}
// try-finally를 사용할 경우
public static String firstLineOfFile(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
// return을 해버리면
return br.readLine();
} finally {
// close를 못한다.
br.close();
}
}
// try-resources를 사용할 경우
public static String firstLineOfFile_r(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
// try-resources에 catch까지 사용할 경우
public static String firstLineOfFile(String path, String defaultVal) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
return defaultVal;
}
}
// try-finally 를 사용할 경우
public static void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buffer = new byte[100];
int n;
// 예외 터지거나 <-- 여기서 터지면 두번째 예외는 잡지 못한다.
while ((n = in.read(buffer)) >= 0) {
// 예외 터지거나
out.write(buffer, 0, n);
}
} finally {
// close 못한다.
out.close();
}
} finally{
// close 못한다.
in.close();
}
}
// try-resources 를 사용할 경우
public static void copy_r(String src, String dst) throws IOException {
try(InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
byte[] buffer = new byte[100];
int n;
// 예외 터지거나 <-- 여기서 터지면 두번째 예외는 잡지 못한다.
while ((n = in.read(buffer)) >= 0) {
// 예외 터지거나
out.write(buffer, 0, n);
}
}
}
}