Skip to content

Commit a924140

Browse files
authored
IO-870: PathUtils.copyFileToDirectory (#728)
* IO-870: PathUtils.copyFileToDirectory span FileSystem. * Add test * null check
1 parent 24142f9 commit a924140

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/main/java/org/apache/commons/io/file/PathUtils.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,18 @@ public static Path copyFile(final URL sourceFile, final Path targetFile, final C
321321
* @see Files#copy(Path, Path, CopyOption...)
322322
*/
323323
public static Path copyFileToDirectory(final Path sourceFile, final Path targetDirectory, final CopyOption... copyOptions) throws IOException {
324-
return Files.copy(sourceFile, targetDirectory.resolve(sourceFile.getFileName()), copyOptions);
324+
// Path.resolve() naturally won't work across FileSystem unless we convert to a String
325+
final Path sourceFileName = sourceFile.getFileName();
326+
if (sourceFileName == null) {
327+
throw new IllegalArgumentException("must have a file name: " + sourceFile);
328+
}
329+
final Path targetFile;
330+
if (sourceFileName.getFileSystem() == targetDirectory.getFileSystem()) {
331+
targetFile = targetDirectory.resolve(sourceFileName);
332+
} else {
333+
targetFile = targetDirectory.resolve(sourceFileName.toString());
334+
}
335+
return Files.copy(sourceFile, targetFile, copyOptions);
325336
}
326337

327338
/**

src/test/java/org/apache/commons/io/file/PathUtilsTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,16 @@ public void testCopyFile() throws IOException {
178178
assertEquals(Files.size(sourceFile), Files.size(targetFile));
179179
}
180180

181+
@Test
182+
public void testCopyFileTwoFileSystem() throws IOException {
183+
try (FileSystem archive = openArchive(Paths.get(TEST_JAR_PATH), false)) {
184+
final Path sourceFile = archive.getPath("next/dir/test.log");
185+
final Path targetFile = PathUtils.copyFileToDirectory(sourceFile, tempDirPath);
186+
assertTrue(Files.exists(targetFile));
187+
assertEquals(Files.size(sourceFile), Files.size(targetFile));
188+
}
189+
}
190+
181191
@Test
182192
public void testCopyURL() throws IOException {
183193
final Path sourceFile = Paths.get("src/test/resources/org/apache/commons/io/dirs-1-file-size-1/file-size-1.bin");

0 commit comments

Comments
 (0)