2

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.

Maaka
  • 35
  • 1
  • 1
  • 4
  • 1
    Do you have permission to write in that directory? Also, I'm afraid you're trying to create it in `C:\resources\`, not where you expect it. – Federico klez Culloca Mar 05 '18 at 11:50
  • Yeah, changing the ROOT string to include the whole path all the way from C: made it work. I guess I got used to how you work with java.io where giving it "/resources" would make it create a file right next to the JAR file – Maaka Mar 05 '18 at 12:15

1 Answers1

3

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215