package homework;

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

public class Demo1 {
public static void main(String[] args) {
		
		try {
			copy1("D://fie1.txt","F://file2.txt");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			copy2(new File("D://fie1.txt"), new File("F://file2.txt"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	//复制文件 source(源文件路径)target目的地路径
	public static  void copy1(String source,String target) throws Exception{
		//读取源文件 字节流输入流
		InputStream is = new FileInputStream(source);
		//写出目标文件 字节流输出流
		OutputStream os = new FileOutputStream(target);
		byte[] bys= new byte[1024];
		//读文件
		int read =-1;
		//一次读取一个字节数组 当返回值-1不读了
		while ((read=is.read())!=-1){
			//写数据
			os.write(bys,0,read);
		}
		//关闭数据
		is.close();
		os.close();
		
	}	
	
	//复制文件 source(源文件路径)target目的地路径
	public static  void copy2(File source,File target)throws Exception {
		
		// 读取源文件 字节流输入流
				InputStream is = new FileInputStream(source);
				// 写出到目标文件 字节流输出流
				OutputStream os = new FileOutputStream(target);
				// 读文件
				int read = -1;
				// 一次读取一个字节
				while ((read = is.read()) != -1) {
					// 写出数据
					os.write(read);
				}
				System.out.println("成功");
				// 关闭资源
				os.close();
				is.close();
	}
}

版权声明:本文为keke77_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/keke77_/article/details/120785166