Java FileOutputStream Create File if not exists
Asked Answered
C

9

236

Is there a way to use FileOutputStream in a way that if a file (String filename) does not exist, then it will create it?

FileOutputStream oFile = new FileOutputStream("score.txt", false);
Crain answered 8/3, 2012 at 15:58 Comment(1)
if anyone is looking for Files.write() way of doing it, try Files.write(Paths.get("./score.txt"), "sometext".getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND);. StandardOpenOptionsDisembowel
C
366

It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. To be sure you probably should first test that the file exists before you create the FileOutputStream (and create with createNewFile() if it doesn't):

File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 
Chickenhearted answered 8/3, 2012 at 16:0 Comment(12)
if the file does not exist, how would I create an empty .txt file?Crain
@StefanDunn with the createNewFile() method, as shown in my example.Chickenhearted
The condition is redundant. According to JavaDoc, createNewFile() itself atomically checks the existence of the file.Jerilynjeritah
@Jerilynjeritah probably we could leave the condition to improve code readabilityHiding
@marcv81 Needless file system access can slow down legitimate java use cases significantly, for example when trying to access a network drive. It also causes a race condition, so you can't guarantee the file doesn't exists by the time you come to writing to it. For both these reasons, it is not advised. If you want to help the reader, leave a comment.Decompensation
@Robino, you are correct about the race condition. My comment was only in response to JopVernooij who was concerned about performance. But I suppose you are also right about performance anyway :)Lammergeier
What is the purpose of the 2nd line? The created file may be deleted between the 2nd line and 3rd line.Regelate
createNewFile() is a total waste of time here. The system will already do that. You're just forcing it to look twice.Derward
Just find out that a file will be created on write, what is needed is to create the dir if not present. For that use 'Kostiantyn Medvid' method.Popcorn
throws "java.io.IOException: No such file or directory"Ammonic
use yourFile.getParentFile().mkdirs() before yourFile.createNewFile(); if you also create directories.Brandt
@Bruno Use it instead of createNewFile(), which is redundant and wasteful here.Derward
H
90

Before creating a file, it's necessary to create all parent directories.

Use yourFile.getParentFile().mkdirs()

Update: Create all parent folders only when they are not already exist. Otherwise it is not necessary.

Haemoid answered 4/9, 2015 at 16:12 Comment(1)
It isn't necessary, or needed as you wrote originally. Only if they don't already exist.Derward
D
40

FileUtils from apache commons is a pretty good way to achieve this in a single line.

FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))

This will create parent folders if do not exist and create a file if not exists and throw a exception if file object is a directory or cannot be written to. This is equivalent to:

File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);

All the above operations will throw an exception if the current user is not permitted to do the operation.

Dysphonia answered 9/7, 2016 at 18:2 Comment(0)
S
28
File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

Pass this f to your FileOutputStream constructor.

Scuttlebutt answered 8/3, 2012 at 16:4 Comment(2)
There's a race condition here... Better to do it as follows: File f = new File("Test.txt"); if (!f.createNewFile()) { System.out.println("File already exists"); }Thrust
This is a complete waste of time. new FileOutputStream(...) already does that, and now you are forcing it to delete the file created here as well.Derward
G
26

You can create an empty file whether it exists or not ...

new FileOutputStream("score.txt", false).close();

if you want to leave the file if it exists ...

new FileOutputStream("score.txt", true).close();

You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.

EDIT: From Java 7 you can create a file, but get more meaningful error messages when it fails.

Path newFilePath = Paths.get(FILE_NAME);
Files.createFile(newFilePath); // throws FileAlreadyExistsException if it exists

This post has many variations. https://www.baeldung.com/java-how-to-create-a-file

Guardsman answered 8/3, 2012 at 16:31 Comment(3)
It throws FileNotFoundException in both cases.Eric
This is woeful, so it returns FileNotFoundException when it should be something like FileNotCreatedException. A totally misleading exception. It'd be like Stephen King saying he can't find his new book instead of saying that he hasn't written it yet!Kerwinn
@AriesConnolly The purpose is to create a file; it only fails if the parent doesn't exist. If anything, it should be PathNotFoundException.Guardsman
E
5

Create file if not exist. If file exits, clear its content:

/**
 * Create file if not exist.
 *
 * @param path For example: "D:\foo.xml"
 */
public static void createFile(String path) {
    try {
        File file = new File(path);
        if (!file.exists()) {
            file.createNewFile();
        } else {
            FileOutputStream writer = new FileOutputStream(path);
            writer.write(("").getBytes());
            writer.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Exoteric answered 19/8, 2016 at 3:51 Comment(1)
This is a complete waste of time. new FileOutputStream(...) already does that, and now you are forcing it to delete the file created here as well.Derward
C
4

Just Giving an alternative way to create the file only if doesn't exists using Path and Files.

Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
    Files.createFile(path);
Files.write(path, ("").getBytes());
Calve answered 14/2, 2018 at 8:42 Comment(1)
This is a complete waste of time. new FileOutputStream(...) already does that, and now you are forcing it to delete the file created here as well.Derward
F
0

You can potentially get a FileNotFoundException if the file does not exist.

Java documentation says:

Whether or not a file is available or may be created depends upon the underlying platform http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

If you're using Java 7 you can use the java.nio package:

The options parameter specifies how the the file is created or opened... it opens the file for writing, creating the file if it doesn't exist...

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

Frith answered 8/3, 2012 at 16:7 Comment(0)
S
0

new FileOutputStream(f) will create a file in most cases, but unfortunately you will get a FileNotFoundException

if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

from Javadoc

I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.

A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f) with Files.newOutputStream(p).

In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p) is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.

Singsong answered 9/2, 2019 at 9:15 Comment(2)
Files.newOutputStream() does not have better error handling than new FileOutputStream. if you think otherwise please substantiate your assertion.Derward
Haha, I could return it back to you: please substantiate your assertion.Singsong

© 2022 - 2024 — McMap. All rights reserved.