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工具類對文件進行復(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);
}
//強制刷出數(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)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
springboot中使用ElasticSearch的詳細教程
這篇文章主要介紹了ElasticSearch在springboot中使用的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05
Java的web開發(fā)中SSH框架的協(xié)作處理應(yīng)用筆記
這篇文章主要介紹了Java的web開發(fā)中SSH框架的協(xié)作處理應(yīng)用筆記,SSH是指Struts和Spring以及Hibernate的框架搭配,需要的朋友可以參考下2015-12-12
Java 關(guān)鍵字 volatile 的理解與正確使用
本文主要介紹 volatile 的使用準則,以及使用過程中需注意的地方,感興趣的朋友一起看看吧2017-06-06
使用Jacoco獲取 Java 程序的代碼執(zhí)行覆蓋率的步驟詳解
這篇文章主要介紹了使用Jacoco獲取 Java 程序的代碼執(zhí)行覆蓋率的步驟詳解,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下2021-03-03
Java微服務(wù)實戰(zhàn)項目尚融寶接口創(chuàng)建詳解
這篇文章主要介紹了Java微服務(wù)實戰(zhàn)項目尚融寶的接口創(chuàng)建流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08

