Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NIO Files.createFile() fails with NoSuchFileException

Tags:

java

file

nio

I am trying to lay down some core files in a dev-test-prod setup. Basically if the file is newer it needs to be copied to the next level as part of the QA process.

I am using Java 8 so I decided to try the NIO Files/Path apis for the first time. I am creaky old, having been programming for 48 years and have used almost exclusively Java since early 1996, and every release since prerelease, so this NIO "enhancement" should not be too hard for me to assimilate, but . . .

FileSystem fs = FileSystems.getDefault();
Path in = fs.getPath(fromFileName);
Path out = fs.getPath(toFileName);

if (Files.exists(out)) {
  FileTime inTime = Files.getLastModifiedTime(in);
  FileTime outTime = Files.getLastModifiedTime(out);

  if (0 > outTime.compareTo(inTime)) {
    Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);
  }
} else {
  Files.createFile(out);
  Files.copy(in, out);
}

I initially just tried Files.copy() without Files.createFile() and got a NoSuchFileException on the copy() call.

I looked a several StackOverflow posts which referred to this, one of which stated authoritatively that copy() will fail if the destination file does not already exist. For the life of me I cannot understand why the designers thought this was a good idea, but so be it. I accordingly added the createFile() call as above (having read the API doc for Files which says that Files.createFile() "Creates a new and empty file, failing if the file already exists." When I ran it again I got exactly the same Exception, but on the createFile() instead of the copy(). Notice the path is inside my home directory on Windows, so no access denied issues should occur. Also NOTHING other than Eclipse containing this project is running on my PC at this time.

java.nio.file.NoSuchFileException: C:\Users\ChrisGage\myproject\site\ttws\css\core.css
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.createFile(Unknown Source)
...

What am I doing wrong?

like image 595
casgage Avatar asked Dec 06 '14 18:12

casgage


1 Answers

Files.copy() (and Files.move() for that matter) is "dumb"; it won't try and do any of the following:

  • copy entire directory hierarchies;
  • move entire directory hierarchies (if the source and target are on different filesystems);
  • create missing directories etc.

You need to do:

final Path tmp = out.getParent();
if (tmp != null) // null will be returned if the path has no parent
    Files.createDirectories(tmp);

prior to copying the file.

like image 80
fge Avatar answered Oct 07 '22 23:10

fge