1.文件的复制:

从一个输入流中读取数据,然后通过输出流写入目标位置

一边读,一边写

2.代码:

package com.lemon;
 
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;
/**
 * 文件复制功能:
 * 从一个输入流中读取数据,然后通过输出流写入目标位置
 *一边读,一边写
 * @author lemonSun
 *
 * 2019年5月4日下午2:17:02
 */
public class FileCopy {
 
	public static void main(String[] args) {
		System.out.println("starting copy...");
		copy("C:\\Users\\Administrator\\Desktop\\新建文件夹 (2)\\壁纸\\123.jpg","F:\\javatest\\123.jpg");
		System.out.println("copy success!");
	}
	
	private static void copy(String src,String target) {
		//创建源文件,和目标文件
		File srcFile = new File(src);
		File targetFile = new File(target);
		//创建输入输出流
		InputStream in =  null;
		OutputStream out = null;
		
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(targetFile);
			byte[] bytes = new byte[1024];
			int len = -1;
			while((len = in.read(bytes))!=-1) {
				out.write(bytes,0,len);
			}
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(in != null) in.close();
				if(out != null) out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
 
}