美文网首页其他
try resource并不适用于返回流的情况

try resource并不适用于返回流的情况

作者: 大旺旺的弟弟小旺旺 | 来源:发表于2022-10-10 09:37 被阅读0次

    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;
        }
    

    相关文章

      网友评论

        本文标题:try resource并不适用于返回流的情况

        本文链接:https://www.haomeiwen.com/subject/fefoartx.html