- Java code
import java.io.*;class WriteTest{ public static void main(String[] args) { FileOutputStream fos=null; FileInputStream fis=null; try { fos=new FileOutputStream("c:\\2.txt"); fis=new FileInputStream("c:\\1.txt"); byte[] buf=new byte[1024]; int len=0; while((len=fis.read(buf))!=-1) { fos.write(buf,0,len); //fos.write(buf); num++; } System.out.println("OK"); } catch (IOException e) { throw new RuntimeException("复制文件失败"); } finally { try { if(fis!=null) fis.close(); } catch (IOException e) { throw new RuntimeException("读取关闭失败"); } try { if(fos!=null) fos.close(); } catch (IOException e) { throw new RuntimeException("写入关闭失败"); } } }}
很多书上都用fos.write(buf,0,len);这样的形式,而我使用fos.write(buf);也可以实现复制,带上0和len参数有什么好处呢?
------解决方案--------------------
buf是存放数据的数组,但是不一定存储满的,所有用带长度的可以保证没有空数据增加
------解决方案--------------------
楼上说的很正确。
采用第一种形式的话的意思就是装了多少数据就写多少,而第二种是不管装满了没,都把整个数组都写进去。
因此第二种会有空数据。
------解决方案--------------------
举个例子吧、楼主自己运行下。然后去C盘看两个文件的内容,就能理解了~~
- Java code
package io; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub byte[] b = new byte[15]; byte bnum = 110; for (int i = 0; i < b.length; i++) { b[i] = bnum++; } ByteArrayInputStream bi = new ByteArrayInputStream(b); FileOutputStream fos; try { System.out .println("-------------用write(byte[] b)来写入文件---------------"); fos = new FileOutputStream(new File("C:\\文件1.txt")); int i = 0; byte[] buffer = new byte[10]; System.out.println("写入数据如下:"); while ((i = bi.read(buffer)) > 0) { p(buffer); fos.write(buffer); } System.out .println("-------------用write(byte[] b,int off,int len)来写入文件---------------"); bi.reset(); fos = new FileOutputStream(new File("C:\\文件1.txt")); i = 0; buffer = new byte[10]; System.out.println("写入数据如下:"); while ((i = bi.read(buffer)) > 0) { p(buffer); fos.write(buffer, 0, i); } fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void p(byte[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print((char) arr[i] + ","); } System.out.println(); } }