1. 程式人生 > >java實現檔案拷貝的幾種方式(全!!)

java實現檔案拷貝的幾種方式(全!!)

浪費了“黃金五年”的Java程式設計師,還有救嗎? >>>   

一、前言:下面例子中,所有異常處理均採用丟擲的形式,各位千萬不要效仿

二、幾種拷貝檔案的方式

    2.1 位元組流的形式

public static void byteCopy(String  sourcePath,String target) throws IOException {
		//1.建立輸入流
		InputStream iStream = new FileInputStream(sourcePath);
		//2.建立輸出流
		OutputStream oStream = new FileOutputStream(target);
		//3.一部分一部分讀出
		byte[] bytes = new byte[10*1024];
		int br;//實際的讀取長度
		while((br =iStream.read(bytes))!=-1) {//判斷是否讀到末尾
			oStream.write(bytes, 0, br);
		}
		//4.清空快取
		oStream.flush();
		//5.關閉流
		if(iStream!=null) {
			iStream.close();
		}
		if(oStream!=null) {
			oStream.close();
		}
}

    2.2 位元組流一次複製完成,缺點是:只能應用於小檔案

public static void byteCopy2(String  sourcePath,String target) throws IOException {
		//1.建立輸入流
		InputStream iStream = new FileInputStream(sourcePath);
		//2.建立輸出流
		OutputStream oStream = new FileOutputStream(target);
		int len = iStream.available();
		//3.全部讀出
		byte[] bytes = new byte[len];
		iStream.read(bytes);
		oStream.write(bytes, 0, len);
		//4.清空快取
		oStream.flush();
		//5.關閉流
		if(iStream!=null) {
			iStream.close();
		}
		if(oStream!=null) {
			oStream.close();
		}
}

    2.3 帶緩衝的位元組流

public static void byteCopy3(String  sourcePath,String target) throws IOException {
		//1.建立輸入流
		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sourcePath));
		//2.建立輸出流
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(target),1024*1024);
		//3.一部分一部分讀出
		byte[] bytes = new byte[10*1024];
		int br;//實際的讀取長度
		while((br =bufferedInputStream.read(bytes))!=-1) {//判斷是否讀到末尾
			bufferedOutputStream.write(bytes, 0, br);
		}
		//4.清空快取
		bufferedOutputStream.flush();
		//5.關閉流
		if(bufferedInputStream!=null) {
			bufferedInputStream.close();
		}
		if(bufferedOutputStream!=null) {
			bufferedOutputStream.close();
		}
}

    2.4 字元流完成,缺點:不能指定字符集,不建議使用

public static void  CharCopy(String  sourcePath,String target) throws IOException{
		Reader reader = new FileReader(sourcePath);
		Writer writer = new FileWriter(target);
		char[] c = new char[10];
		int read;
		while((read = reader.read(c))!=-1) {
			writer.write(c, 0, read);
		}
		writer.flush();
		if(reader!=null) {
			reader.close();
		}
		if(writer!=null) {
			writer.close();
		}
}

    2.5 標準的字元流實現,能指定字符集,一行一行讀出,true表示追加

public static void  CharCopy2(String  sourcePath,String target) throws IOException{
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourcePath), "utf-8"));
		PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(target,true),"utf-8"));
		String line;              
		while((line = bufferedReader.readLine())!=null) {
			printWriter.write(line+"\n");
		}
		if(bufferedReader != null) {
			bufferedReader.close();
		}
		if(printWriter != null) {
			printWriter.close();
		}
}

    2.6 NIO實現檔案拷貝(用transferTo的實現 或者transferFrom的實現),這裡是transferTo的實現。

public static void  NIOCopyFile(String  source,String target) throws  Exception{
        //1.採用RandomAccessFile雙向通道完成,rw表示具有讀寫許可權
        RandomAccessFile fromFile = new RandomAccessFile(source,"rw");
        FileChannel fromChannel = fromFile.getChannel();

        RandomAccessFile toFile = new RandomAccessFile(target,"rw");
        FileChannel toChannel = toFile.getChannel();

        long count =  fromChannel.size();
        while (count > 0) {
            long transferred = fromChannel.transferTo(fromChannel.position(), count, toChannel);
            count -= transferred;
        }
        if(fromFile!=null) {
            fromFile.close();
        }
        if(fromChannel!=null) {
            fromChannel.close();
        }
}

2.7 NIO實現檔案自身內容拷貝(追加到末尾)

public static void main(String[] args)  throws Exception {
        //1.獲取雙向通道
        RandomAccessFile file = new RandomAccessFile("C:\\Users\\num11\\Desktop\\grade.txt","rw");
        //2.得到通道
        FileChannel channel = file.getChannel();
        //3.定義快取
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        if(channel.read(byteBuffer)!= -1){ //判斷是否讀到末尾
            //4.反轉
            byteBuffer.flip();
            channel.write(byteBuffer);
            byteBuffer.clear();
        }
        if(file != null){
            file.close();
        }
}

2.8 java.nio.file.Files.copy()實現檔案拷貝,其中第三個引數決定是否覆蓋

public  static  void  copyFile(String  source,String target){
        Path sourcePath      = Paths.get(source);
        Path destinationPath = Paths.get(target);

        try {
            Files.copy(sourcePath, destinationPath,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            //something else went wrong
            e.printStackTrace();
        }
}