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

使用如下格式将a.txt复制到b.txt结果发现字节数不一样,为什么类?
public static void main(String[] args) {
try{
byte[] buffer=new byte[1024];
FileInputStream fileInputStream=new FileInputStream(new File(args[0]));
FileOutputStream fileOutputStream=new FileOutputStream(new File(args[1]));
System.out.println(fileInputStream.available());
while(true){
if(fileInputStream.available()<1024){
int remain=-1;
while(((remain=fileInputStream.read())!=-1))
{
fileInputStream.read(buffer);
fileOutputStream.write(buffer);
}
break;//离开当前for while swtich
}
else{
fileOutputStream.flush();
fileInputStream.read(buffer);
fileOutputStream.write(buffer);
}
}
fileInputStream.close();
fileOutputStream.close();
System.out.println("复制完成");
}
catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("USING 中文");
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

------解决方案--------------------
比较习惯这种:

int i = -1;
byte[] buffer=new byte[1024];

FileInputStream fileInputStream=new FileInputStream(new File(args[0]));
FileOutputStream fileOutputStream=new FileOutputStream(new File(args[1]));

while((i = fileInputStream.read(buffer,0,1024)) != -1) {
fileOutputStream.write(buffer,0,i);
}
...
close();
------解决方案--------------------
byte[] buffer=new byte[1024];
每次都是读取1024再写入,这会出现问题,假如最后一个循环他只读取到20个字节,这时候你写入的还是1024字节,其中有1004个字节是空字节。
------解决方案--------------------
Java code

while(((remain=fileInputStream.read())!=-1))
{
fileInputStream.read(buffer);
fileOutputStream.write(buffer);
}

------解决方案--------------------
探讨
真的哦,我还是不太明白为什么会出垃圾数据。。。。。