Select a file name using Files.copy ()

I have a temporary 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 select the destination file name.

So far, I have some solutions that do not satisfy me:

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

There may be a cleaner solution. Do you know that?

+7
java
source share
1 answer

With John's help, I discovered that /path/to/archive/dir was actually a file. The error message is misleading because it says that /path/to/archive/dir/file.xml not a directory, even if the problem arose from /path/to/archive/dir .

Steps to play on 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 will receive an 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) 
+1
source share

All Articles