如何为给定路径创建文件(包括文件夹)?

Sri*_*vas 48 java android file

我正在从网上下载一个zip文件.它包含文件夹和文件.使用解压缩他们ZipInputstreamZipEntry.Zipentry.getName给出文件名为htm/css/aaa.htm.

所以我正在创造新的 File(zipentry.getName);

但问题是抛出异常:File not found.我知道它正在创建子文件夹htmcss.

我的问题是:如何通过传递上述路径创建包含其子目录的文件?

Sea*_*oyd 108

用这个:

File targetFile = new File("foo/bar/phleem.css");
File parent = targetFile.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
    throw new IllegalStateException("Couldn't create dir: " + parent);
}
Run Code Online (Sandbox Code Playgroud)

虽然您可以file.getParentFile().mkdirs()不检查结果,但最好的做法是检查操作的返回值.因此,首先检查现有目录,然后检查是否成功创建(如果它尚不存在).

参考:


And*_*ejs 12

你可以使用Google的库在Files类的几行中完成它:

Files.createParentDirs(file);
Files.touch(file);
Run Code Online (Sandbox Code Playgroud)

https://code.google.com/p/guava-libraries/


Vad*_*rev 5

Java NIO API Files.createDirectories

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Path path = Paths.get("/folder1/folder2/folder3");
Files.createDirectories(path);

Run Code Online (Sandbox Code Playgroud)