一、文件拷貝簡介
文件拷貝是常見的文件操作,是將指定目錄下的文件以及文件夾複製到指定的目錄,這樣可以方便地對文件進行備份或者移動等操作。在Java程序開發中,實現文件拷貝也非常簡單,Java提供了多種方式來實現文件的複製操作,例如使用Java IO類等。
二、Java文件拷貝的實現
Java文件拷貝可以通過以下幾種方式實現:使用Java IO類、使用Java NIO類、使用Apache Commons IO類庫的FileUtils類以及使用Java 7的NIO 2的Files類等。
三、使用Java IO類進行文件拷貝
Java IO類是Java提供的輸入輸出類,可以通過它們進行文件的輸入輸出。以下是使用Java IO類進行文件拷貝的示例代碼:
/**
* 拷貝文件
* @param sourcePath 原路徑
* @param destPath 目標路徑
*/
public static void copy(String sourcePath, String destPath) throws IOException {
File source = new File(sourcePath);
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(source);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四、使用Java NIO類進行文件拷貝
Java NIO類是一組全新的I/O類庫,它提供了新的輸入輸出方法。以下是使用Java NIO類進行文件拷貝的示例代碼:
/**
* 拷貝文件
* @param sourcePath 原路徑
* @param destPath 目標路徑
*/
public static void copy(String sourcePath, String destPath) throws IOException {
FileChannel source = new FileInputStream(sourcePath).getChannel();
FileChannel dest = new FileOutputStream(destPath).getChannel();
try {
dest.transferFrom(source, 0, source.size());
} finally {
source.close();
dest.close();
}
}
五、使用Apache Commons IO類庫的FileUtils類進行文件拷貝
Apache Commons IO類庫是一個開源的Java類庫,提供了很多常用的I/O操作。以下是使用Apache Commons IO類庫的FileUtils類進行文件拷貝的示例代碼:
/**
* 拷貝文件
* @param sourcePath 原路徑
* @param destPath 目標路徑
*/
public static void copy(String sourcePath, String destPath) throws IOException {
File source = new File(sourcePath);
File dest = new File(destPath);
FileUtils.copyFile(source, dest);
}
六、使用Java 7的NIO 2的Files類進行文件拷貝
Java 7的NIO 2類提供了新的文件操作API,包括文件複製、文件夾創建、文件刪除等操作。以下是使用Java 7的NIO 2的Files類進行文件拷貝的示例代碼:
/**
* 拷貝文件
* @param sourcePath 原路徑
* @param destPath 目標路徑
*/
public static void copy(String sourcePath, String destPath) throws IOException {
Path source = Paths.get(sourcePath);
Path dest = Paths.get(destPath);
Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
}
七、總結
使用Java實現文件拷貝有多種方式,如Java IO類、Java NIO類、Apache Commons IO類庫的FileUtils類以及Java 7的NIO 2的Files類等。每種方式都有同時有優點和缺點,可以根據具體情況選擇適合自己的實現方式。
原創文章,作者:YIVF,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/144997.html
微信掃一掃
支付寶掃一掃