- Java code
public static void main(String[] args) { long startTime = System.nanoTime(); try { File file = new File("F:\\old.gif"); File newfile = new File("F:\\new.gif"); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newfile); byte[] b = new byte[1024]; while(in.read(b,0,1024)!=-1){ out.write(b,0,1024); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } long time = System.nanoTime()-startTime; System.out.println(time/(1000*1000)+"ms"); }
比如原文件大小是3.5K,新文件就是4K,这要怎么解决。
------解决方案--------------------
先读文件长度,到最后不够1k时,读入余数字节
------解决方案--------------------
把while(in.read(b,0,1024)!=-1){
out.write(b,0,1024);
}
改成
int length = 0;
while((length = in.read(b))!=-1){
out.write(b,0,length);
}
应为在你最后一次读取的时候,可能没有1024字节,但是你还是写入了1024字节,
我在这里加了一个length的变量,就是每次读写的实际长度。
这种写法应该是IO操作的常规做法吧!