Java復(fù)制文件常用的三種方法
復(fù)制文件的三種方法:
1、Files.copy(path, new FileOutputStream(dest));。
2、利用字節(jié)流。
3、利用字符流。
代碼實現(xiàn)如下:
package com.tiger.io; import java.io.*; import java.nio.file.*; /** * 復(fù)制文件的三種方式 * @author tiger * @Date */ public class CopyFile { public static void main(String[] args) throws IOException, IOException { Path path = Paths.get("E:","17-06-15-am1.avi"); String dest = "E:\\Copy電影.avi"; copy01(path, dest); String src = "E:\\[Java典型應(yīng)用徹查1000例:Java入門].pdf"; String dest1 = "E:\\CopyFile.pdf"; copy02(src, dest1); //copy03(src, dest1); } /** * 利用Files工具copy * @param path * @param dest * @throws IOException * @throws IOException */ public static void copy01(Path path,String dest) throws IOException, IOException{ //利用Files工具類對文件進(jìn)行復(fù)制,簡化編程,只需要寫一句。 Files.copy(path, new FileOutputStream(dest)); } /** * 利用字節(jié)流復(fù)制 * @param src * @param dest * @throws IOException */ public static void copy02(String src,String dest) throws IOException{ InputStream is = new BufferedInputStream(new FileInputStream(src)); OutputStream os = new BufferedOutputStream(new FileOutputStream(dest)); //文件拷貝u,-- 循環(huán)+讀取+寫出 byte[] b = new byte[10];//緩沖大小 int len = 0;//接收長度 //讀取文件 while (-1!=(len = is.read(b))) { //讀入多少,寫出多少,直到讀完為止。 os.write(b,0,len); } //強(qiáng)制刷出數(shù)據(jù) os.flush(); //關(guān)閉流,先開后關(guān) os.close(); is.close(); } /** * 字符流復(fù)制 * @param src * @param dest * @throws IOException */ public static void copy03(String src,String dest) throws IOException{ //字符輸入流 BufferedReader reader = new BufferedReader(new FileReader(src)); //字符輸出流 BufferedWriter writer = new BufferedWriter(new FileWriter(dest)); char[] cbuf = new char[24]; int len = 0; //邊讀入邊寫出 while ((len = reader.read(cbuf)) != -1) { writer.write(cbuf, 0, len); } //關(guān)閉流 writer.close(); reader.close(); } }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
Session過期后自動跳轉(zhuǎn)到登錄頁面的實例代碼
這篇文章主要介紹了Session過期后自動跳轉(zhuǎn)到登錄頁面實例代碼,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-06-06詳解Spring Cloud中Hystrix 線程隔離導(dǎo)致ThreadLocal數(shù)據(jù)丟失
這篇文章主要介紹了詳解Spring Cloud中Hystrix 線程隔離導(dǎo)致ThreadLocal數(shù)據(jù)丟失,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件
這篇文章主要介紹了mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot系列教程之dubbo和Zookeeper集成方法
這篇文章主要介紹了SpringBoot系列教程之dubbo和Zookeeper集成方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09