您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么在Java中對文件進(jìn)行復(fù)制,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
復(fù)制文件的三種方法:
1、Files.copy(path, new FileOutputStream(dest));。
2、利用字節(jié)流。
3、利用字符流。
代碼實(shí)現(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(); } }
上述就是小編為大家分享的怎么在Java中對文件進(jìn)行復(fù)制了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。