Java FileOutputStream如果不存在则创建文件

Ste*_*unn 178 java file-io file new-operator fileoutputstream

有没有办法以一种方式使用FileOutputStream,如果文件(String filename)不存在,那么它会创建它吗?

FileOutputStream oFile = new FileOutputStream("score.txt", false);
Run Code Online (Sandbox Code Playgroud)

tal*_*las 286

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

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

  • 这种情况是多余的.根据[JavaDoc](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#createNewFile%28%29),`createNewFile()`本身以原子方式检查存在的文件. (54认同)
  • @deville它导致性能损失,所以,不. (19认同)
  • @aztek可能我们可以留下条件来提高代码的可读性 (8认同)
  • @StefanDunn使用`createNewFile()`方法,如我的例子所示. (3认同)
  • 如果该文件不存在,我将如何创建一个空的.txt文件? (2认同)
  • createNewFile()在这里完全浪费时间。系统将已经执行该操作。您只是强迫它看起来两次。 (2认同)

Kos*_*vid 53

在创建文件之前,需要创建所有父目录.

使用 yourFile.getParentFile().mkdirs()


Pet*_*rey 23

您可以创建一个空文件,无论它是否存在......

new FileOutputStream("score.txt", false).close();
Run Code Online (Sandbox Code Playgroud)

如果你想保留文件,如果它存在...

new FileOutputStream("score.txt", true).close();
Run Code Online (Sandbox Code Playgroud)

如果尝试在不存在的目录中创建文件,则只会获得FileNotFoundException.

  • 它会在两种情况下抛出`FileNotFoundException`. (2认同)

Sha*_*dne 20

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

将此传递f给您的FileOutputStream构造函数.

  • 这里有一个竞争条件......最好按如下方式进行: File f = new File("Test.txt"); if (!f.createNewFile()) { System.out.println("文件已经存在"); } (4认同)

Nik*_*ahu 18

文件实用程序从Apache的百科全书是在一个单一的线,实现这样的好方法.

FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))
Run Code Online (Sandbox Code Playgroud)

这将创建父文件夹(如果不存在)并创建文件(如果不存在)并在文件对象是目录或无法写入时抛出异常.这相当于:

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);
Run Code Online (Sandbox Code Playgroud)

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


nhu*_*uvy 5

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

/**
 * 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();
    }
}
Run Code Online (Sandbox Code Playgroud)