文件的拷贝,方法操作

package com.cyj.Byte;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile2 {
	
	public static void main(String[] args) {
		
		String srcpath = "C:\\Users\\Chyjrily\\Documents\\Tencent Files\\2323010676\\FileRecv\\中国\\江苏省.txt";
		String destpath = "E:\\爱情公寓全集\\浙江.txt";
		try {
			CopyFile(srcpath,destpath);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件不存在|关闭流失败|拷贝失败");
		}
	}


	
	
	/**
	 * CopyFile  (拷贝文件方法)
	 * @param srcpath  需要拷贝的文件地址
	 * @param destpath 需要输出拷贝的文件地址
	 * @throws IOException 
	 */
	
	    public static void CopyFile(String srcpath, String destpath) throws IOException {
		
		//创建联系源(文件必须存在),创建拷贝地址(文件名不存在)
		File src = new File(srcpath);
		//浙江.txt文件没有,这个就是输出的文件名
		File dest = new File(destpath);
		
		if(! src.isFile()) {
			System.out.println("不是文件类型地址");   //用户
			throw new IOException("不是文件类型地址");//程序员
		}
		
		
		//选择流
		InputStream is = new FileInputStream(src);    //输入流
		OutputStream os = new FileOutputStream(dest); //输出流
		
		//文件的拷贝  循环的读取和输出
		
		//读取
		byte[] flush = new byte[1024];  //每次读取1024个字节,写就是1K
		int len = 0;//将len定义为0,如果最后一次没有读取到数据,返回-1,终止循环
		while(-1 != (len = is.read(flush))) {
			//边读,边写
			os.write(flush, 0, len);//如果最后一次读不满,输出实际的flush	
		}
		
		os.flush(); //强制刷出,防止没有显示
		
		//关闭流(原则:先打开的后关闭)
		os.close();
		is.close();
		
	}

}

猜你喜欢

转载自blog.csdn.net/qq_42036616/article/details/80983126