简体   繁体   English

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

[英]Java FileOutputStream Create File if not exists

有没有办法以一种方式使用 FileOutputStream ,如果文件(字符串文件名)不存在,那么它将创建它?

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

It will throw a FileNotFoundException if the file doesn't exist and cannot be created ( doc ), but it will create it if it can.如果文件不存在且无法创建( doc ),它将抛出FileNotFoundException ,但如果可以,它将创建它。 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):为了确保您可能应该在创建FileOutputStream之前首先测试该文件是否存在createNewFile()如果不存在,则使用createNewFile()创建):

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

Before creating a file, it's necessary to create all parent directories.在创建文件之前,有必要创建所有父目录。

Use yourFile.getParentFile().mkdirs()使用yourFile.getParentFile().mkdirs()

Update: Create all parent folders only when they are not exist.更新:仅当它们不存在时才创建所有父文件夹。 Otherwise it is not necessary.否则没有必要。

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.将此f传递给您的FileOutputStream构造函数。

You can create an empty file whether it exists or not ...无论是否存在,您都可以创建一个空文件...

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

if you want to leave the file if it exists ...如果你想离开文件,如果它存在......

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

You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.如果您尝试在不存在的目录中创建文件,您只会收到 FileNotFoundException。

FileUtils from apache commons is a pretty good way to achieve this in a single line. 文件实用程序从Apache的百科全书是一个不错的方式一行来实现这一目标。

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.如果当前用户没有权限进行操作,上述所有操作都会抛出异常。

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

Just Giving an alternative way to create the file only if doesn't exists using Path and Files.仅在使用路径和文件不存在时才提供另一种创建文件的方法。

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(f) will create a file in most cases, but unfortunately you will get a FileNotFoundException new FileOutputStream(f)在大多数情况下会创建一个文件,但不幸的是你会得到一个 FileNotFoundException

if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason如果文件存在但是是一个目录而不是常规文件,不存在但无法创建,或者由于任何其他原因无法打开

from Javadoc 来自 Javadoc

I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.我换言之,可能有很多情况您会得到 FileNotFoundException ,意思是“无法创建您的文件”,但您将无法找到文件创建失败的原因。

A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling.一种解决方案是删除对文件 API 的任何调用,并改用文件 API,因为它提供了更好的错误处理。 Typically replace any new FileOutputStream(f) with Files.newOutputStream(p) .通常用Files.newOutputStream(p)替换任何new FileOutputStream(f) Files.newOutputStream(p)

In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p) is a good way to make sure your file is created properly and if not you would know why it didn't work.在您确实需要使用 File API 的情况下(例如因为您使用 File API 的外部接口),使用Files.createFile(p)是确保正确创建文件的好方法,否则您将知道为什么它没有用。 Some people commented above that this is redundant.上面有人评论说这是多余的。 It is true, but you get better error handling which might be necessary in some cases.确实如此,但您可以获得更好的错误处理,这在某些情况下可能是必要的。

You can potentially get a FileNotFoundException if the file does not exist.如果文件不存在,您可能会收到FileNotFoundException

Java documentation says: Java 文档说:

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文件是否可用或是否可以创建取决于底层平台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:如果您使用的是 Java 7,则可以使用 java.nio 包:

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... options 参数指定文件的创建或打开方式...它打开文件进行写入,如果文件不存在则创建该文件...

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM