javaiotemporary-filesjava.nio.filenosuchfileexception

NoSuchFileException when using java.nio.file.Files.createTempDirectory


I have an issue when trying to create a temporary directory with java.nio.file.Files.createTempDirectory. I keep getting NoSuchFileException when trying to create the directory.

Here is my code:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TempFileTesting {
   private static final String ROOT = "/resources/";

   public static void main(String[] args) throws Exception{
      Path root = Paths.get(ROOT);
      Path tempDir = Files.createTempDirectory(root, "dir");
      Path tempFile = Files.createTempFile(tempDir, "t1", "t2");
   }
}

When I do this I get a NoSuchFileException on the line calling "createTempDirectory" despite the root Path clearly being created successfully. The resources directory does exist.

The StackTrace looks like this:

java.nio.file.NoSuchFileException: \resources\dir170003182480656885
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(WindowsFileSystemProvider.java:504)
at java.nio.file.Files.createDirectory(Files.java:674)
at java.nio.file.TempFileHelper.create(TempFileHelper.java:136)
at java.nio.file.TempFileHelper.createTempDirectory(TempFileHelper.java:173)
at java.nio.file.Files.createTempDirectory(Files.java:950)
at filetestingstuff.testers.TempFileTesting.main(TempFileTesting.java:15)

Full Path: "C:\Users\Admin\Desktop\eclipse-oxygen\workspace\FileStuff\resources"

Does anyone have any idea why exactly this causes this Exception to occur? I am grateful for any advice, no matter how small.


Solution

  • You specified "/resources/" as path to the directory in which to create the temporary directory.
    First, it is not a valid format for windows. As I test it creates the temp directory at the root of the drive where windows is installed.

    Besides what you want is a relative path : "resources" to the working folder of the JVM that is C:\Users\Admin\Desktop\eclipse-oxygen\workspace\FileStuff. Note that the trailing / is not required any longer.
    So that should solve your issue :

    private static final String ROOT = "resources";     
    

    At last, you should avoid using folders as C:\Users to contain your Java source code. You may have right issues too.
    They should be located in a not specific Windows directory.