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

关于outputstream的问题
package work_3_1_2013;

import java.io.*;

public class Sceond {

public static void main(String[] args) {
InputStream in,in2;
OutputStream out;
try{
in = new FileInputStream("e:\\a.txt");
out = new FileOutputStream("d:\\b.txt");
in2 = new FileInputStream("e:\\abc.txt");
byte[] buff = new byte[1024];

int len2 = 0;
int len = 0;
while ((len = in.read(buff)) != -1){
len2 = len;
out.write(buff, 0, len);
}
in.close();
len = 0;
while ((len = in2.read(buff)) != -1){
System.out.println(len);
out.write(buff, len2, len);
}
out.flush();
in2.close();
}catch(FileNotFoundException e){

} catch (IOException e) {

}
}
}

调试之后,abc.txt文件内的文字无法读入b.txt内 只有一堆空白
= =求解。。。

------解决方案--------------------
方法签名:
public void write(byte[] b,
                  int off,
                  int len)
将指定字节数组中从偏移量 off 开始的 len 个字节写入此输出流。write(b, off, len) 的常规协定是:将数组 b 中的某些字节按顺序写入输出流;元素 b[off] 是此操作写入的第一个字节,b[off+len-1] 是此操作写入的最后一个字节。
你的偏移量len2长度已经超过了abc.txt的长度了,所以写第一个字节buff[len2]时就已经是空白,往后写依然是空白。应该是这么回事。