是否有一种方法来使用FileOutputStream的方式,如果一个文件(字符串文件名)不存在,那么它将创建它?

FileOutputStream oFile = new FileOutputStream("score.txt", false);

当前回答

File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

将这个f传递给FileOutputStream构造函数。

其他回答

如果不存在,创建文件。如果文件退出,清除其内容:

/**
 * 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();
    }
}
File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

将这个f传递给FileOutputStream构造函数。

如果文件不存在且无法创建(doc),它将抛出FileNotFoundException,但如果可以,它将创建该文件。为了确保你可能应该在创建FileOutputStream之前首先测试文件是否存在(如果它不存在,则使用createNewFile()创建):

File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing 
FileOutputStream oFile = new FileOutputStream(yourFile, false); 

在创建文件之前,有必要创建所有父目录。

用yourFile mkdirs getParentFile()。()

更新:只在父文件夹不存在时创建所有父文件夹。否则就没有必要了。

你可以创建一个空文件,不管它是否存在…

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

如果你想离开文件,如果它存在…

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

如果您试图在一个不存在的目录中创建文件,则只会得到一个FileNotFoundException。

编辑:在Java 7中,你可以创建一个文件,但是当文件失败时,你会得到更有意义的错误消息。

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

这篇文章有很多变化。https://www.baeldung.com/java-how-to-create-a-file