方法一:java.nio.file 包下的Files,Paths,Path 类,非常简单的实现。
public static void main(String[] args){
Path path = Paths.get("D:\\temp\\a\\b\\c");
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
方法二:由于输出文件的需要,自己写了一个保证输出路径正确的小程序,使用了迭代。
import java.io.File;
public class FileUtils {
/**
* 检查目录的正确性,如果有文件夹不存在,则创建,直到创建的文件目录存在为止
* @param path
* @param filename
* @throws Exception
*/
public static boolean checkFile(File f) throws Exception{
String path = f.getParent();
String name = f.getName();
mkPath(path);
if(f.exists()){
if(f.length() > 0){
return false;
// f.deleteOnExit();
// f = new File(path + name);
// f.createNewFile();
}
}else {
File file = new File(path);
if(!(file.isDirectory() && file.exists())){
file.mkdir();
}
f.createNewFile();
}
return true;
}
public static void mkPath(String path){
File f = new File(path);
if(f.exists()){
if(f.isDirectory()){
return;
}else {
f.delete();
f.mkdir();
}
} else {
mkPath(f.getParent());
f.mkdir();
}
}
}
原创。。。转帖请标明出处,期待交流