简体   繁体   中英

Chose file name with Files.copy()

I have a temp file in /tmp that I want to archive somewhere so I tried:

import java.nio.file.Files;
[...]

Path source = Paths.get("/tmp/path/to/file_123456789.xml");
Path destination = Paths.get("/path/to/archive/dir/file.xml");
Files.copy(source, destination).

This fails because :

/path/to/archive/dir/file.xml is not a directory

I know it! But I just want to chose the destination file's name.

Up to now, I have some solutions which do not satisfy me:

  • Create a temp directory with Files.createTempDirectory then move the temp file in it, rename it then move it to the destination directory.
  • Copy the temp file in the archive directory then rename it there. But if the rename fails, I have some junk in the archive directory.
  • Create an empty file in the archive directory and manually copy the content of the source file in it.

A cleaner solution probably exists. Do you know it?

With the help of Jon, I found that /path/to/archive/dir was actually a file. The error message is misleading because it says that /path/to/archive/dir/file.xml is not a directory even if the problem came from /path/to/archive/dir .

Steps to reproduce under linux :

1) create the file /tmp/fakedir

touch /tmp/fakedir

2) In Java, execute this piece of code :

Path tempFile = Files.createTempFile("test", "test");
Files.copy(tempFile, Paths.get("/tmp/fakedir/destination.xml"));

You get the error message :

Exception in thread "main" java.nio.file.FileSystemException: /tmp/fakeDir/destination.xml: is not a directory
  at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91)
  at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
  at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
  at sun.nio.fs.UnixCopyFile.copyFile(UnixCopyFile.java:243)
  at sun.nio.fs.UnixCopyFile.copy(UnixCopyFile.java:581)
  at sun.nio.fs.UnixFileSystemProvider.copy(UnixFileSystemProvider.java:253)
  at java.nio.file.Files.copy(Files.java:1271)
  at Test.main(Test.java:17)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:483)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM