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

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

当前回答

如果文件不存在且无法创建(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); 

其他回答

如果文件不存在且无法创建(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); 
File f = new File("Test.txt");
if(!f.exists()){
  f.createNewFile();
}else{
  System.out.println("File already exists");
}

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

来自apache commons的FileUtils是在一行中实现这一目标的好方法。

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

如果不存在,则创建父文件夹;如果不存在,则创建文件;如果文件对象是目录或不能写入,则抛出异常。这相当于:

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

如果当前用户不允许执行上述所有操作,则所有操作都将抛出异常。

如果文件不存在,您可能会得到一个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

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

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