Java IO1 复制粘贴文件

来源:互联网 发布:网络交友平台有哪些 编辑:程序博客网 时间:2024/05/02 18:26
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 blocke.printStackTrace();//出错才执行} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {//都执行if(in != null) {//成功打开 intry {in.close();} catch (IOException e2) {// TODO: handle exceptionin = null;}}}}}


import java.io.File;public class Test {public static void main(String args[]) {Copy.cp(new File("a.txt"), new File("b.txt"));}}


原创粉丝点击