有没有办法以某种方式使用 FileOutputStream,如果文件(字符串文件名)不存在,那么它将创建它?
FileOutputStream oFile = new FileOutputStream("score.txt", false);
有没有办法以某种方式使用 FileOutputStream,如果文件(字符串文件名)不存在,那么它将创建它?
FileOutputStream oFile = new FileOutputStream("score.txt", false);
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);
在创建文件之前,有必要创建所有父目录。
采用yourFile.getParentFile().mkdirs()
更新:仅在不存在时创建所有父文件夹。否则没有必要。
来自 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);
如果不允许当前用户进行操作,上述所有操作都会抛出异常。
File f = new File("Test.txt");
if(!f.exists()){
f.createNewFile();
}else{
System.out.println("File already exists");
}
将此传递f
给您的FileOutputStream
构造函数。
无论是否存在,您都可以创建一个空文件...
new FileOutputStream("score.txt", false).close();
如果您想保留该文件(如果存在)...
new FileOutputStream("score.txt", true).close();
如果您尝试在不存在的目录中创建文件,您只会收到 FileNotFoundException。
如果不存在则创建文件。如果文件退出,清除其内容:
/**
* 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();
}
}
仅在使用路径和文件不存在时才提供另一种创建文件的方法。
Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
Files.createFile(path);
Files.write(path, ("").getBytes());
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
new FileOutputStream(f)
在大多数情况下会创建一个文件,但不幸的是你会得到一个 FileNotFoundException
如果文件存在但是是目录而不是常规文件,不存在但无法创建,或者由于任何其他原因无法打开
换句话说,在很多情况下,您会得到 FileNotFoundException 的意思是“无法创建您的文件”,但您将无法找到文件创建失败的原因。
一种解决方案是删除对文件 API 的任何调用,并改用文件 API,因为它提供了更好的错误处理。通常将 any 替换new FileOutputStream(f)
为Files.newOutputStream(p)
.
在您确实需要使用 File API 的情况下(例如,因为您使用 File 的外部接口),使用Files.createFile(p)
是确保正确创建文件的好方法,如果不是,您会知道它为什么不起作用。上面有人评论说这是多余的。确实如此,但您会获得更好的错误处理,这在某些情况下可能是必要的。