NoSuchFileException when creating a file using nio

21.5k views Asked by At

I am trying to create a new file using java nio, and I'm running into a createFile error. Error looks like this:

 createFile error: java.nio.file.NoSuchFileException: /Users/jchang/result_apache_log_parser_2015/06/09_10:53:49

code segment looks like this:

 String filename = "/Users/jchang/result_apache_log_parser_" + filename_date;
        Path file = Paths.get(filename);
        try {
            Files.createFile(file);
        } catch (FileAlreadyExistsException x) {
            System.err.format("file named %s" +
                    " already exists%n", file);
        } catch (IOException x) {
            System.err.format("createFile error: %s%n", x);
        }

Anyone have any idea how to fix this? Thanks for your help!

3

There are 3 answers

2
PapaBuduiit On BEST ANSWER

I would say that Turing85 was correct. Your filename_date variable has slashes in it. So /Users/jchang/result_apache_log_parser_2015 has to exist as a directory. That is the cause of the NoSuchFileException, missing directory.

1
harunurhan On

As many said, you need to create intermediate directories, like ../06/..

So use this, before creating the file to create dirs which don't exist,

Files.createDirectories(mPath.getParent());

So your code should be:

    Path file = Paths.get(filename);
    try {
        Files.createDirectories(file.getParent());
        Files.createFile(file);
    } catch (FileAlreadyExistsException x) {
        System.err.format("file named %s" +
                " already exists%n", file);
    } catch (IOException x) {
        System.err.format("createFile error: %s%n", x);
    }
0
Turing85 On

Your code has at least two problems. First: you have path delimiters in your filename (/). Second: at least under Windows, your solution has illegal characters within the filname (:).

To get rid of the first problem, you can go down two routes: a) create all the folders you need or b) change the delimiters to something different. I will explain both.

To create all folders to a path, you can simply call

Files.createDirectories(path.getParent());

where path is a file (important!). By calling getParent() on file, we get the folder, in which path resides. Files.createDirectories(...) takes care of the rest.

b) Change the delimiters: Nothing easier than this:

String filename =  "/Users/jchang/result_apache_log_parser_"
                 + filename_date.replace("/", "_")
                                .replace(":", "_");

This should yield something like /User/jchang/result_apache_parser_2015_06_09_10_53_29

With b) we have taken care of the second problem as well.

Now lets set it all together and apply some minor tricks of nio:

String filename =  "/Users/jchang/result_apache_log_parser_"
                 + filename_date.replace('/', '_')
                                .replace(':', '_');

Path file = Paths.get(filename);
try {
    // Create sub-directories, if needed.
    Files.createDirectories(file.getParent());
    // Create the file content.
    byte[] fileContent = ...;
    // We do not need to create the file manually, let NIO handle it.
    Files.write(file
                , fileContent
                // Request permission to write the file
                , StandardOpenOption.WRITE
                // If the file exists, append new content
                , StandardOpenOption.APPEND
                // If the file does not exist, create it
                , StandardOpenOption.CREATE);
} catch (IOException e) {
    e.printStackTrace();
}

For more information about nio click here.