更新時間:2022-11-22 09:38:38 來源:動力節點 瀏覽1659次
在本文中,我們將介紹在 Java 中復制文件的常用方法。
首先,我們將使用標準IO和NIO.2 API,以及兩個外部庫:commons-io和guava。
首先,要使用 java.io API復制文件,我們需要打開一個流,遍歷內容并將其寫出到另一個流:
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (
InputStream in = new BufferedInputStream(
new FileInputStream(original));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
實現這樣的基本功能需要做很多工作。
對我們來說幸運的是,Java 改進了它的核心 API,我們有了使用NIO.2 API復制文件的更簡單方法。
使用NIO.2可以顯著提高文件復制性能,因為NIO.2使用較低級別的系統入口點。
讓我們仔細看看 Files. copy()方法有效。
copy()方法使我們能夠指定表示復制選項的可選參數。默認情況下,復制文件和目錄不會覆蓋現有的,也不會復制文件屬性。
可以使用以下復制選項更改此行為:
REPLACE_EXISTING –替換文件(如果存在)
COPY_ATTRIBUTES –將元數據復制到新文件
NOFOLLOW_LINKS –不應跟隨符號鏈接
NIO.2 Files類提供了一組重載的copy ()方法,用于在文件系統中復制文件和目錄。
讓我們看一個使用帶有兩個Path參數的copy()的例子:
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath)
.equals(Files.readAllLines(copied)));
}
請注意,目錄副本是淺表的,這意味著目錄中的文件和子目錄不會被復制。
使用 Java 復制文件的另一種常見方法是使用commons-io庫。
首先,我們需要添加依賴:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
然后,要復制文件,我們只需要使用 FileUtils 類中定義的copyFile ()方法。該方法采用源文件和目標文件。
讓我們看一下使用copyFile()方法的 JUnit 測試:
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File(
"src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
最后,我們將看一下 Google 的 Guava 庫。
同樣,如果我們想使用 Guava ,我們需要包含依賴項:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
這是 Guava 復制文件的方式:
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File("src/test/resources/copiedWithGuava.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習