Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchFileException when creating a file using nio

Tags:

java

file-io

nio

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!

like image 962
jstnchng Avatar asked Jun 09 '15 14:06

jstnchng


People also ask

What is no such file exception?

Class NoSuchFileExceptionChecked exception thrown when an attempt is made to access a file that does not exist.

Which methods are found in the NIO 2 files class?

Java NIO Files class contains static methods that is used for manipulating files and directories and those methods mostly works on Path object.

What is import Java NIO file files?

Core Java bootcamp program with Hands on practice Java NIO package provide one more utility API named as Files which is basically used for manipulating files and directories using its static methods which mostly works on Path object.


2 Answers

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);
    }
like image 175
harunurhan Avatar answered Nov 15 '22 12:11

harunurhan


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.

like image 43
Turing85 Avatar answered Nov 15 '22 13:11

Turing85