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

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

问题描述

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

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

推荐答案

如果文件不存在且无法创建(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天全站免登陆