1. 程式人生 > 實用技巧 >Java利用緩衝位元組流複製檔案

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;
	}
}