大家好:
第一次发帖,向大家讨教一个问题,请多多指教
最近想看下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以上就可以了。这咋回事啊?谢谢。

解决方案 »

  1.   

    你把原来cc.txt文件内容和ss.txt文件内容比对下,多出来的内容是什么?
    把cc.txt内容和ss.txt内容贴出来看看吧
      

  2.   

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

  3.   

    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();
    }
    }
    }
    你这样写是错误的。
    应该这样写.
    try {
    while ((tempchar = str.read(by)) != -1) {
    out.write(by,0,tempchar);
    out.flush();
    }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    str.close();
    out.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    这样就读多少,写多少,不会出现多余的现象