package demo.trydemo;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* try使用示例
*/
public class TryDemo {
//jdk7版本使用方式
@Test
public void tryJdk7() {
InputStreamReader reader = new InputStreamReader(System.in);
try {
reader.read(); //读取流的操作:略
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//jdk8版本使用方式
@Test
public void tryJdk8() {
try (InputStreamReader reader = new InputStreamReader(System.in)) {
reader.read();//读取流的操作:略
} catch (IOException e) {
e.printStackTrace();
}
}
//jdk9版本使用方式
@Test
public void tryJdk9() {
InputStreamReader reader = new InputStreamReader(System.in);
//可以直接try引用,这时 reader是final的,常量不可变
try (reader) {
reader.read();//读取流的操作:略
} catch (IOException e) {
e.printStackTrace();
}
}
//jdk9 多个资源try使用
@Test
public void tryJDK9() {
InputStreamReader reader = new InputStreamReader(System.in);
OutputStreamWriter writer = new OutputStreamWriter(System.out);
//可以直接try引用,这时 reader是final的,常量不可变
//多个资源用分号隔开
try (reader; writer) {
reader.read();//读取流的操作:略
writer.append("");//模拟流的操作:略
} catch (IOException e) {
e.printStackTrace();
}
}
}