Java-流已关闭

Java-流已关闭,java,exception,Java,Exception,我正在使用以下代码运行另一个jar: (我正在更新某些部分的gui,所以不要感到困惑。)我在这里得到一个IO异常(流关闭): 这是完整的代码: if(!data.serverStarted()){ try{ data.updateConsole("Starting server!"); String fileDir = data.dir + File.separator + "craftbukkit.jar";

我正在使用以下代码运行另一个jar: (我正在更新某些部分的gui,所以不要感到困惑。)我在这里得到一个IO异常(流关闭):

这是完整的代码:

if(!data.serverStarted()){


        try{
            data.updateConsole("Starting server!");
            String fileDir = data.dir + File.separator + "craftbukkit.jar";
            Process proc = Runtime.getRuntime().exec("java -Xmx2048M -jar "+"craftbukkit.jar"+" -o true --nojline");
            data.setOutputStream(proc.getOutputStream());
            InputStream is = proc.getErrorStream();
        }catch(IOException ex){
            ex.printStackTrace();
        }
        BufferedReader readr = new BufferedReader(new InputStreamReader(is));
        data.setServerStarted(true);
        String line;
        while(data.serverStarted()){
            try {
                if((line = readr.readLine()) != null){
                    data.updateConsole(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    readr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }else{
        data.updateConsole("You have already started your server!");
    }

您有一个
while
循环,在每次通过时关闭
readr
。下次它到达
try
块时,
readr
关闭。也许您打算在
循环时在
周围放置
try/catch
块?

您正在将读卡器关闭在从中读取的循环中。您需要在循环之外关闭它:

try {        
    String line;
    while (data.serverStarted() && ((line = readr.readLine()) != null)) {
        try {
            data.updateConsole(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} finally {
    try {
        readr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

我很惊讶这段代码竟然可以编译

您在开始时声明实际的InputStream
在try/catch中,但这使得它仅在该块中可见。因此,下面几行给BufferedReader的内容是其他内容,很可能不是您认为的内容

此外,您的
while(data.serverStarted())
不会检查流是否仍处于打开状态,稍后您只会使用一个
if
检查(同样,如果流处于打开状态,则不检查),因此您最多只能读取一行


我有一种感觉,您在编写此代码时遇到了一个糟糕的OutofOffeeException

我很乐意对任何实际问题进行修正,如果选民愿意发表评论的话。
try {        
    String line;
    while (data.serverStarted() && ((line = readr.readLine()) != null)) {
        try {
            data.updateConsole(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} finally {
    try {
        readr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}