在Thread中关闭了Java InputStream [英] Java InputStream closed in Thread

查看:205
本文介绍了在Thread中关闭了Java InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从线程中的InputStream读取。

I am trying to read from an InputStream in a Thread.

Thread应该运行的类看起来像这样

The class that the Thread should run looks like this

static private class Runner implements Runnable {

    private InputStream fis;
    private OutputStream fos;

    public Runner(InputStream fis, OutputStream fos) throws IOException {

        int blu = fis.available();

        System.out.println(blu);

        this.fis = fis;

        int bla = this.fis.available();

        System.out.println(bla);
        this.fos = fos;
    }

    @Override
    public void run() {

        try {
            int bla = fis.available();

            System.out.println(bla);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(fis);
        System.out.println(fos);

    }

}

线程得到像这样创建

final Runnable runnable = new Runner(fis, fos);
final Thread thread = new Thread(runnable);
thread.start();

并且在线程上应运行run方法。但是一旦执行它就会得到错误

And on the Thread should run the run method. But as soon as it is executed I get the Error

java.nio.channels.ClosedChannelException

我调试它并将InputStream设置为关闭。

I debugged it and the InputStream is set to closed.

为什么InputStream在Thread中关闭?有没有我应该使用的替代方案?

Why does the InputStream get closed in the Thread? Is there an alternative I should use?

编辑:

我忘了提到它们是在一个开放的像这样尝试块,然后主要功能结束。

I forgot to mention that they are opened in a try block like this and the main function is over after that.

try (InputStream fis = Files.newInputStream(sourcePath)) {
        try (OutputStream fos = Files.newOutputStream(sinkPath)) {

            final Runnable runnable = new Runner(fis, fos);
            final Thread thread = new Thread(runnable);
            thread.start();
        }

    }


推荐答案

try-with-resources 块将关闭当块退出时各自的流。当您只计划使用块内的流时,这很好。但是因为你想在块结束后继续在另一个线程中使用流,所以去掉块。

Those try-with-resources blocks will close their respective streams when the block exits. This is great when you only plan to use the streams inside the blocks. But since you want to continue using the streams in another thread after the blocks end, get rid of the blocks.

InputStream  fis = Files.newInputStream (sourcePath);
OutputStream fos = Files.newOutputStream(sinkPath);

final Runnable runnable = new Runner(fis, fos);
final Thread   thread   = new Thread(runnable);
thread.start();

这篇关于在Thread中关闭了Java InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆