日期:2014-05-20  浏览次数:20872 次

关于java io奇怪问题
大家好:
第一次发帖,向大家讨教一个问题,请多多指教
最近想看下java io流,写了个小例子将c:\\cc.txt文件内容读出来写入c:\\ss.txt文件中区,代码很简单,只有几行,代码如下:
public static void main(String[] args) throws FileNotFoundException {
String res = "c:\\cc.txt";
File file = new File(res);
InputStream str = new FileInputStream(file);
OutputStream out = new FileOutputStream("c:\\ss.txt");
byte[] by = new byte[10];
int tempchar = 0;
try {
while ((tempchar = str.read(by, 0, by.length)) != -1) {
out.write(by, 0, by.length);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
str.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
可出现问题了,运行完成之后ss.txt文件内容比cc.txt文件内容要多,这是怎么回事?当我把byte数组大小改为100以上就可以了。这咋回事啊?谢谢。

------解决方案--------------------
out.write(by, 0, by.length);
这个不对,你要写进去,应该是读到多少字节,写多少字节进去,如果是最后一次读,它可能没有读到那么字节,那你的数组后面就有很多不是原来文件中的字节。所以有问题呀。
应该改为:
out.write(by, 0, tempchar);