Saturday 15 June 2013

java - Chose file name with Files.copy() -


I have a temporary file in / tmp which I want to store anywhere I tried:

  import java.nio.file.files; [...] Path Source = Path. ("/ 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! But I just have to choose the name of the destination file.

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

  • Create a temporary directory with Files.createTempDirectory then it contains Move the temporary file, rename it, move it to the destination directory.
  • Copy the temporary file to the archive directory, then rename it there. But if the name change fails, then 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 into it.

A cleaner solution probably exists. Do you know this?

With the help of John, I found that / path / to / archive / dir was actually a file error message is confusing because it states that /path/to/archive/dir/file.xml is not a directory even if the problem is / path / to / Archive / dir .

The steps to reproduce under Linux:

1) File / tmp / fakedir

2) In Java, execute this piece of code:

  path tempFile = Files.createTempFile ("test", "test" / tmp / fakedir   

"Files.copy" (tempFile, path. ("/ Tmp / fakedir / destination.xml"));

You get an error message:

  exception in thread "main" java.nio.file.FileSystemException: /tmp/fakeDir/destination.xml: sun.nio.fs.UnixException.translateToIOException (UnixException.java:91) sun.nio.fs.UnixException. RethrowAsIOException (UnixException.java:102) at sun.nio.fs.UnixException.rethrowAsIOException (UnixException Is not a directory java: 107) sun.nio.fs.UnixCopyFile.copyFile (UnixCopyFile.java:243) sun.nio.fs.UnixCopyFile.copy (UnixCopyFile.java:581) on sun.nio.fs.UnixFileSystemProvider.copy (at UnixFileSystemProvider on SunkreflectkNativeMethodAccessorImplkinvoke0 (Native method) at java.nio.file.Files.copy (Files.java:1271) on Test.main (Test.java:17) on sun.reflect .java: 253) (NativeMethodAccessorImpl.java:62) on .NativeMethodAccessorImpl.invoke sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) com on java.lang.reflect.Method.invoke (Method.java:483). On intellij.rt Aksekyutionkappli Ktiankappamainkman (Appamainkjawa:l20)  

No comments:

Post a Comment