在线程中写文件的程序报 java.io.IOException: 句柄无效。不知道为什么,请帮忙看看。谢谢

程序报 java.io.IOException: 句柄无效。不知道为什么,请帮忙看看。
java.io.IOException: 句柄无效。
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:247)
at com.hippo.common.custsystem.Test$1.write(WindowsCmd.java:228)
at com.hippo.common.custsystem.Test$1.run(WindowsCmd.java:220)
at java.lang.Thread.run(Thread.java:595)

附上程序

class Test{
try {
FileOutputStream out = new FileOutputStream("F:\\temp2\\result.txt", true);
Test.writeSomething(out, "test ");
out.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
/** @todo Handle this exception */
ex.printStackTrace();
}

}

public final static void writeSomething(final OutputStream output, final String line) throws
IOException {
Thread thread = new Thread(new Runnable(){
public void run() {
try {
this.write();
output.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}

public void write() throws IOException {
output.write(line.getBytes());
}
});
thread.start();
}//end of method

}

哥们,你的程序问题出在多线程上,由于你的writesomething方法里new了一个新的线程,所以主线程接着执行到了调用处将out输出流关闭了,造成你的子线程无法操作。一个简单的办法就是将主线程延迟关闭。你试着加一条语句:

Test.writeSomething(out, "test ");
Thread.sleep(1000);
out.close();

应该就能解决问题了
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-08-24
同意楼上观点,主线程关闭了流,导致出错。

建议你在关闭前要wait所有的线程都已经关闭。
第2个回答  2010-08-24
主线程把输出流关闭了,
第3个回答  2010-08-24
多线程文件操作感觉很危险
不知道你的需求何在?

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网