Java InputStream closed in thread
•
Java
I tried to read from the InputStream in the thread
The class that 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); } }
This is how thread is created
final Runnable runnable = new Runner(fis,fos); final Thread thread = new Thread(runnable); thread.start();
And the run method should be run on the thread But once it is executed, it will get an error
java.nio.channels.ClosedChannelException
I debugged it and set InputStream to off
Why close InputStream in thread? Is there an alternative I should use?
Edit:
I forgot to mention that they were opened in such a test block, and then the main function ended
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(); } }
Solution
When blocks exit, those try - with - resources blocks close their respective streams This is good when you only plan to use streams within blocks But because you want to continue using the stream in another thread after the block ends, remove the block
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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码