Java NIO Files. Createfile() failed with nosuchfileexception

I tried to put some core files in the dev - Test - prod setup Basically, if the document is newer, it needs to be copied to the next level as part of the quality inspection process

I use Java 8, so I decided to try NiO files / path APIs for the first time I am a terrible old man. I have been programming for 48 years. Since the beginning of 1996, I have almost completely used java, and every version since its release, so this NiO "enhancement" should not be too difficult to absorb, 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 just tried files Copy() without files Createfile() and get a nosuchfileexception on the copy() call

I read several stackoverflow posts that mention this, one of which states that copy () will fail if the target file does not exist For my life, I don't understand why designers think this is a good idea, but so Accordingly, I added the createfile() call as described above (the API file of the file has been read, which says that files. Createfile() "create a new and empty file, and fail if the file already exists" When I run it again, I say exactly the same exception, but in CreateFile () instead of copy () Note that the path is in the home directory of windows, so access should not be denied In addition to eclipse, which contains this project, is there anyone else running this on my PC

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 on earth did I do wrong?

Solution

Files. Copy() (and files. Move()) are "dumb"; It does not attempt and do any of the following:

>Copy the entire directory hierarchy; > Move the entire directory hierarchy (if the source and destination are on different file systems); > Create missing directories, etc

You need to:

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

Before copying files

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>