Java 错误消息:流已关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22611092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:51:08  来源:igfitidea点击:

error message : stream closed

javaerror-handlingbufferedreaderioexception

提问by KNU

Upon running following code under class FlightSearch

在类下运行以下代码时 FlightSearch

String moreSearch = "y";
    List<Flight> resultList;

    // load initial flight data into DB
    if (!init()) {
        return;
    }
    // A background thread to monitor changes in csv repository
    FileListner fl = new FileListner();
    fl.start();

    do {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        // main thread gets input
        Input inputQuery = new Input();
        try {
            inputQuery.getQuery();
        } catch (InvalidException e1) {
            e1.getMessage();
        } finally {
            fl.stopThread();
        }
        // main thread STARTs processing task as background monitors csv
        // repo
        QueryProcessor processor = new QueryProcessor();
        resultList = null;
        resultList = processor.matchQuery(inputQuery);

        displayResult(resultList, inputQuery.getFlightClass());

        System.out
                .println("More Flight Query ? Press n/N to exit. Anyother key to continue searching.");

        try {
            moreSearch = br.readLine(); // LINE 56
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    } while (!moreSearch.equalsIgnoreCase("n"));

    System.out.println("Thank You !!!");

I get following error :

我收到以下错误:

java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162)
at java.io.BufferedInputStream.read(BufferedInputStream.java:325)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at com.myApp.FlightSearch.main(FlightSearch.java:56)

I have also tried moving

我也试过搬家

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

moving out of do-while loop but in vain.

退出 do-while 循环但徒劳无功。

采纳答案by taringamberini

The problem

问题

The problem is that you execute the br.close()that, as javadoc states, closes the stream and releases any system resources associated with it.

问题在于您执行了br.close()javadoc 所述的关闭流并释放与其关联的任何系统资源的操作

Just for a quick verification comment out the:

只是为了快速验证注释掉:

if (br != null) {
//    try {
//        br.close();
//    } catch (IOException e) {
//        // TODO Auto-generated catch block
//        e.printStackTrace();
//    }
}

and you can answer sany times you want without any exception.

你可以随时回答,s没有任何例外。

A solution

一个办法

A solution is closing the buffer reader after all reads are terminated:

一个解决方案是在所有读取终止后关闭缓冲区读取器:

    String moreSearch = null;
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    try {
        do {
            // ...
            System.out.println("More Flight Query ? Press n/N to exit. Anyother key to continue searching.");
            moreSearch = br.readLine();
        } while (!moreSearch.equalsIgnoreCase("n"));

    } catch (IOException e) {
        Logger.getLogger(FlightSearch.class.getName()).log(Level.SEVERE, "Cant read line from a System.in based BufferedReader", e);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ignoreMe) {
                Logger.getLogger(FlightSearch.class.getName()).log(Level.SEVERE, "Can't close a System.in based BufferedReader", ignoreMe);
            }
        }
    }

回答by JonK

Your issue is that you're calling br.close()in the finallyblock where you read a line from the buffer. When you close a Stream, any stream that was wrapped by the one you closed is also closed. As a result, your first iteration through the do { } while ()loop is closing the System.in InputStream, which you cannot then reopen.

您的问题是您在从缓冲区读取一行br.close()finally块中调用。当您关闭 a 时Stream,任何被您关闭的流包裹的流也将关闭。因此,您在do { } while ()循环中的第一次迭代将关闭System.in InputStream,然后您无法重新打开它。

To avoid this, you can use a CloseShieldInputStreamfrom Apache Commons to wrap System.inbefore you wrap it with the InputStreamReader. This will allow you to close the BufferedReader(which will also close the InputStreamReaderand the CloseShieldInputStream) without triggering the closure of System.in.

为了避免这种情况,你可以使用CloseShieldInputStreamApache的共享来包装System.in你用它包装之前InputStreamReader。这将允许您关闭BufferedReader(这也将关闭InputStreamReaderCloseShieldInputStream)而不触发 的关闭System.in

See bmargulies answer here: Closing BufferedReader and System.in

请参阅此处的 bmargulies 答案:关闭 BufferedReader 和 System.in

回答by KNU

After making changes as suggested in previous answermy code didn't tun but with slight more changes as shown below, my code compiled and run just fine

按照上一个答案中的建议进行更改后,我的代码没有调整,但有如下所示的更多更改,我的代码编译并运行得很好

    try {
        do {
            // main thread gets input
            Input inputQuery = new Input();
            inputQuery.getQuery();

            // main thread STARTs processing task as background monitors csv
            // repo
            QueryProcessor processor = new QueryProcessor();
            resultList = null;
            resultList = processor.matchQuery(inputQuery);

            displayResult(resultList, inputQuery.getFlightClass());
            System.out
                    .println("More Flight Query ? Press n/N to exit. Anyother key to continue searching.");
            moreSearch = br.readLine();

        } while (!moreSearch.equalsIgnoreCase("n"));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InvalidException e1) {
        e1.getMessage();
    } finally {
        fl.stopThread();
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println("Thank You !!!");
}

thanks for help.

感谢帮助。