Java FileOutputStream创建文件(如果不存在) [英] Java FileOutputStream Create File if not exists

查看:116
本文介绍了Java FileOutputStream创建文件(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to use FileOutputStream in a way that if a file (String filename) does not exist, then it will create it?

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


推荐答案

它会抛出一个 FileNotFoundException 如果该文件不存在并且无法创建( doc ),但它可以创建它。确保您可能应该首先测试该文件是否存在,然后再创建 FileOutputStream (并使用 createNewFile()如果没有):

It will throw a FileNotFoundException if the file doesn't exist and cannot be created (doc), but it will create it if it can. 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):

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

这篇关于Java FileOutputStream创建文件(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆