java 如何自动创建丢失的文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10585851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to automatically create a missing folder?
提问by user595234
In java, I need to write a string into a new file, like 'c:\test\upload\myfile.txt', if the 'upload' folder is not existing, it will automatically create it. how to do it ? Apache Commons IO has this API ?
在java中,我需要将一个字符串写入一个新文件,比如'c:\test\upload\myfile.txt',如果'upload'文件夹不存在,它会自动创建它。怎么做 ?Apache Commons IO 有这个 API 吗?
回答by Mattias Isegran Bergander
File file = new File(...);
file.mkdirs(); //for several levels, without the "s" for one level
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("...");
Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.
Returns:true if and only if the directory was created, along with all necessary parent directories; false otherwise
创建由此抽象路径名命名的目录,包括任何必要但不存在的父目录。请注意,如果此操作失败,则它可能已成功创建了一些必要的父目录。
返回:当且仅当创建目录以及所有必需的父目录时才返回true;否则为假
See File.mkdirs()and File.mkdir()
回答by JeanValjean
In additionto the accepted answer, since the question also mentioned the library Apache Common IO, I report in the following a solution by using this nice library:
在除了要接受的答案,因为这个问题也提到了图书馆Apache的通用IO,我在下面的解决方案通过使用这个漂亮的图书馆报告:
File file = new File("... the directory path ...");
FileUtils.forceMkdir(file);
This solution uses the class FileUtils
, from package org.apache.commons.io
and the method forceMkdir
, that "Makes a directory, including any necessary but nonexistent parent directories".
此解决方案使用FileUtils
来自包的类org.apache.commons.io
和方法forceMkdir
,即“创建目录,包括任何必要但不存在的父目录”。
回答by Mark Jeronimus
new File(fileToSave.getParent()).mkdirs();
It returns a boolean to check if the making succeeded (will fail if the disk is full or if a file exists with the name 'upload', etc)
它返回一个布尔值来检查制作是否成功(如果磁盘已满或是否存在名称为“上传”的文件等,则会失败)