try resource作用域只在try的内部,超过范围,流就已经关闭
public static void main(String[] args) {
App app = new App();
app.test();
}
public void test(){
FileInputStream stream = getStream1();
try {
int read = stream.read();
System.out.println(read);
} catch (IOException e) {
e.printStackTrace();
}
}
public FileInputStream getStream(){
try {
FileInputStream fileInputStream = new FileInputStream(".gitignore");
return fileInputStream;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* java.io.IOException: Stream Closed
* at java.io.FileInputStream.read0(Native Method)
* at java.io.FileInputStream.read(FileInputStream.java:207)
* at com.tony.puzzle.App.test(App.java:17)
* at com.tony.puzzle.App.main(App.java:11)
* @return
*/
public FileInputStream getStream1(){
try (FileInputStream fileInputStream = new FileInputStream(".gitignore");){
return fileInputStream;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
网友评论