是否有一种方法来使用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构造函数。

其他回答

只是提供了一种替代方法来创建文件,如果不存在使用路径和文件。

Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
    Files.createFile(path);
Files.write(path, ("").getBytes());

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

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

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

/**
 * 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();
    }
}

如果文件不存在,您可能会得到一个FileNotFoundException。

Java文档说:

文件是否可用或是否可以创建取决于 底层平台 http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

如果你使用的是Java 7,你可以使用Java。nio包:

options参数指定如何创建或打开文件…它打开文件进行写入,如果文件不存在则创建该文件… http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

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

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