Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchFileException in Files.newInputStream with StandardOpenOption.CREATE

Tags:

java

nio

I am trying to open a file for reading or create the file if it was not there. I use this code:

String location = "/test1/test2/test3/";
new File(location).mkdirs();
location += "fileName.properties";
Path confDir = Paths.get(location);
InputStream in = Files.newInputStream(confDir, StandardOpenOption.CREATE);
in.close();

And I get java.nio.file.NoSuchFileException

Considering that I am using StandardOpenOption.CREATE option, the file should be created if it is not there.

Any idea why I am getting this exception?

like image 547
Arashsoft Avatar asked Nov 21 '16 22:11

Arashsoft


2 Answers

It seems that you want one of two quite separate things to happen:

  1. If the file exists, read it; or
  2. If the file does not exist, create it.

The two things are mutually exclusive but you seem to have confusingly merged them. If the file did not exist and you've just created it, there's no point in reading it. So keep the two things separate:

    Path confDir = Paths.get("/test1/test2/test3");
    Files.createDirectories(confDir);
    Path confFile = confDir.resolve("filename.properties");

    if (Files.exists(confFile))
        try (InputStream in = Files.newInputStream(confFile)) {
            // Use the InputStream...
        }
    else
        Files.createFile(confFile);

Notice also that it's better to use "try-with-resources" instead of manually closing the InputStream.

like image 133
Klitos Kyriacou Avatar answered Sep 28 '22 08:09

Klitos Kyriacou


Accordingly to the JavaDocs you should have used newOutputStream() method instead, and then you will create the file:

OutputStream out = Files.newOutputStream(confDir, StandardOpenOption.CREATE);
out.close();

JavaDocs:

// Opens a file, returning an input stream to read from the file.
static InputStream newInputStream(Path path, OpenOption... options)

// Opens or creates a file, returning an output stream that
// may be used to write bytes to the file.
static OutputStream newOutputStream(Path path, OpenOption... options)

The explanation is that OpenOption constants usage relies on wether you are going to use it within a write(output) stream or a read(input) stream. This explains why OpenOption.CREATE only works deliberatery with the OutputStream but not with InputStream.

NOTE: I agree with @EJP, you should take a look to Oracle's tutorials to create files properly.

like image 28
another Avatar answered Sep 28 '22 08:09

another