编程小龙的博客哟

Java利用缓冲字节流复制文件

利用缓冲字节流能够更高效的读写文件。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;

/**
 * 
 * 3、使用缓冲字节流对文件进行复制(封装成方法)
 * @author lzp
 * @Date 2020年7月27日
 */
public class Test3 {
	public static void main(String[] args) {
		if(copy("C:\\Users\\lzp\\Desktop\\b.txt", "C:\\Users\\lzp\\Desktop\\lp66.txt")) {
			System.out.println("复制成功!!");
		}else {
			System.out.println("复制失败!!");
		}
	}
	
	public static boolean copy(String srcPath,String targetPath) {//被复制的原文件路径和复制的目标路径
		File srcFile = new File(srcPath);
		File targetFile = new File(targetPath);
		
		//字节IO流
		InputStream in = null;
		OutputStream out = null;
		//字节缓存流
		BufferedInputStream bIn = null;
		BufferedOutputStream bOut = null;
		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(targetFile);
			bIn = new BufferedInputStream(in);
			bOut = new BufferedOutputStream(out);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		}
		
		//读取数据
		byte[] buff = new byte[1024];
		try {
			while(bIn.read(buff)!=-1) {
				bOut.write(buff);
			}
			System.out.println("复制完成!!");
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
		try {
			if(bIn!=null) {
				bIn.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			if(bOut!=null) {
				bOut.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return true;
	}
}
posted @ 2020-07-28 09:34  编程小龙  阅读(300)  评论(0)    收藏  举报

(づ ̄3 ̄)づ╭❤~