winnie90
winnie90
2016-08-22 02:58
采纳率: 100%
浏览 6.0k
已采纳

java多线程报错 java.io.IOException: Stream closed

虽然程序可以正确的讲读取到的信息输出到文本文件 但是报错:java.io.IOException: Stream closed
不知道是什么原因 菜鸟请各位帮忙看一下
代码如下:
package test;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test implements Runnable{
String lineString;
public Test(String line){
this.lineString = line;
}
static FileWriter writer;
static FileReader reader;
public static void main(String[] args) throws IOException {
try {
reader = new FileReader("/Users/tcredit-0002/Desktop/car.txt");
Scanner scanner = new Scanner(reader);
String lineString;
writer = new FileWriter("/Users/tcredit-0002/Desktop/hebei.txt");
// TODO Auto-generated method stub
ExecutorService pool = Executors.newFixedThreadPool(3);
while(scanner.hasNext()){
lineString = scanner.nextLine();
pool.execute(new Test(lineString));
}
scanner.close();
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

@Override
public void run() {
    try {
        writeResult(lineString);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static synchronized void writeResult(String lineString) throws InterruptedException{
    try {
        writer.write(lineString+"\r\n");
        writer.flush();
        System.out.println(lineString);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • yuyubingMan
    yuyubingMan 2016-08-22 03:06
    已采纳

    IO流被提前关闭了,你把关闭IO流放到finally里面就好了

    点赞 评论
  • Sorive
    Heleninsa 2016-08-22 05:45

    你采用了多线程,每次循环都会开启新的一个线程。当while结束后,并非所有的线程都执行完毕。你关闭流后,剩下的线程可能执行对流的操作因此产生异常

    点赞 1 评论
  • lyyybz
    码界一棵葱 2016-08-22 06:45
     try{
    
    }catch(Exception e){
    
    }finally{
    
    }
    

    所有的收尾工作都在finally中干!

    点赞 评论

相关推荐