Java FileOutputStream Create File if not exists

2019-01-03 23:34发布

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);

8条回答
Rolldiameter
2楼-- · 2019-01-03 23:58

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

查看更多
小情绪 Triste *
3楼-- · 2019-01-04 00:00
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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-04 00:02

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); 
查看更多
Evening l夕情丶
5楼-- · 2019-01-04 00:02

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.

查看更多
男人必须洒脱
6楼-- · 2019-01-04 00:07

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

Use yourFile.getParentFile().mkdirs()

查看更多
萌系小妹纸
7楼-- · 2019-01-04 00:08

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();
    }
}
查看更多
登录 后发表回答