import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array; public class Copy { /** * 文件复制 * @param * @param * */ public Copy() { // TODO Auto-generated constructor stub } public static void cp(File src, File desc) { //使用输入流从源读取(接收) InputStream in = null; OutputStream out = null; try { //打开目标文件 in = new FileInputStream(src); out = new FileOutputStream(desc); //读,写 byte[] buf = new byte[4]; //in.read() 读一个字节,返回的是字节(读到的数据本身) //in.read(buf) 读取放入buf,会一直往前读,读完了,缓冲满了,返回的是读到的数据的数量 int size ; while(-1 != (size = in.read(buf))) { // 如果这样的话会出现倒数第二次留下的以前的脏数据 // out.write(buf); //每次写入剩下的size,避免写入的了脏垃圾 out.write(buf, 0, size); size = in.read(); System.out.println(Arrays.toString(buf)); } System.out.println("ok"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //出错才执行 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //都执行 if(in != null) { //成功打开 in try { in.close(); } catch (IOException e2) { // TODO: handle exception in = null; } } } } }
import java.io.File; public class Test { public static void main(String args[]) { Copy.cp(new File("a.txt"), new File("b.txt")); } }