13

What is the Java 7 or Java 8 way to create a file if that does not exists?

emotionull
  • 595
  • 2
  • 8
  • 24
  • 1
    AFAIK Java 8 doesn't change the way we work with files. – Nir Alfasi Jan 10 '15 at 15:42
  • 2
    @alfasin Java 7 (and therefore Java 8 as well) has changed it immensely with java.nio.file; and today, unfortunately, it is still underused – fge Jan 10 '15 at 15:44
  • @fge Quite true. I'll remove it. – Biffen Jan 10 '15 at 15:47
  • Possible duplicate of [how to create a file in Java only if one doesn't already exist?](http://stackoverflow.com/questions/1556127/how-to-create-a-file-in-java-only-if-one-doesnt-already-exist). – Joe Jan 10 '15 at 15:57
  • @Joe like I said in an earlier comment, this question does not provide any solution with java.nio.file. This is 2015! What is more, this question explicity mentions Java 7+. – fge Jan 10 '15 at 16:02
  • For what purpose? Normally you don't just create files, you write to them, in which case you just use a `new FileOutputStream(...)` or whatever. Asking for a Java 7 or 8 solution requires motivation. – user207421 Jan 10 '15 at 22:35

2 Answers2

27

Not sure what you want, but for instance:

try {
    Files.createFile(thePath);
} catch (FileAlreadyExistsException ignored) {
}

And there are other solutions; for instance:

if (!Files.exists(thePath, LinkOption.NOFOLLOW_LINKS))
    Files.createFile(thePath);

Note that unlike File, these will throw exceptions if file creation fails! And relevant ones at that (for instance, AccessDeniedException, ReadOnlyFileSystemException, etc etc)

See here for more information. Also see why you should migrate to java.nio.file, quickly.

fge
  • 119,121
  • 33
  • 254
  • 329
1

You can do

File f = new File("pathToYourFile");
if(!f.exists() && !f.isDirectory())
{
    f.createNewFile()
}

If you want to use NIO.2 you can use methods Files class.

boolean exists(Path path,LinkOption. . . options)
Path createTempFile(Path dir, String prefix,String suffix, FileAttribute<?>. . . attrs)
createFile(Path path, FileAttribute<?>... attrs)

As fge has mentioned in the comments createNewFile() methods returns boolean value denoting if file was actually created or not. Unfortunately there is no way to know why it failed. In fact this is one of the reason NIO.2 I/O APIs were introduced.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289