更新時間:2022-06-10 11:10:59 來源:動力節(jié)點 瀏覽1903次
在Java教程中,大家學到了很多關(guān)于Java的課程,接下來動力節(jié)點小編將介紹在 Java 中復(fù)制文件的常用方法。
首先,我們將使用標準IO和NIO.2 API,以及兩個外部庫:commons-io和guava。
首先,要使用 java.io API復(fù)制文件,我們需要打開一個流,遍歷內(nèi)容并將其寫入另一個流:
@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())));
}
實現(xiàn)這樣的基本功能需要做很多工作。
對我們來說幸運的是,Java 改進了它的核心 API,并且我們有了使用NIO.2 API復(fù)制文件的更簡單的方法。
使用NIO.2可以顯著提高文件復(fù)制性能,因為NIO.2使用較低級別的系統(tǒng)入口點。
讓我們仔細看看 Files. copy()方法有效。
copy()方法使我們能夠指定表示復(fù)制選項的可選參數(shù)。默認情況下,復(fù)制文件和目錄不會覆蓋現(xiàn)有文件和目錄,也不會復(fù)制文件屬性。
可以使用以下復(fù)制選項更改此行為:
REPLACE_EXISTING –如果文件存在則替換它
COPY_ATTRIBUTES –將元數(shù)據(jù)復(fù)制到新文件
NOFOLLOW_LINKS –不應(yīng)遵循符號鏈接
NIO.2 Files類提供了一組重載的copy ()方法,用于在文件系統(tǒng)中復(fù)制文件和目錄。
讓我們看一個使用帶有兩個Path參數(shù)的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)));
}
請注意,目錄副本很淺,這意味著目錄中的文件和子目錄不會被復(fù)制。
使用 Java 復(fù)制文件的另一種常用方法是使用commons-io庫。
首先,我們需要添加依賴:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
最新版本可以從Maven Central下載。
然后,要復(fù)制文件,我們只需要使用 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>
最新版本可以在 Maven Central上找到。
這是 Guava 復(fù)制文件的方式:
@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())));
}
如果想了解更多相關(guān)知識,可以關(guān)注一下動力節(jié)點的Guava教程,里面有更豐富的知識等著大家去學習,希望對大家能夠有所幫助。
相關(guān)閱讀