java.io.File mkdir() 和 mkdirs()的差别

来源:互联网 发布:淘宝图片多少像素 编辑:程序博客网 时间:2024/04/30 04:31

mkdirs()可以成功建立多级文件夹, mkdir()只能成功建立一级的文件夹,多层目录就不能创建成功

private String path = "D:/folder/subFolder";private String fileName = "temp.txt";@Testpublic void testMkdir() throws Exception {    String tempPath = path.concat(File.separator).concat(fileName);    File file = new File(tempPath);    if (!file.getParentFile().exists()) {        file.getParentFile().mkdir();    }    file.createNewFile();}@Testpublic void testMkdirs() throws Exception {    String tempPath = path.concat(File.separator).concat(fileName);    File file = new File(tempPath);    if (!file.getParentFile().exists()) {        file.getParentFile().mkdirs();    }    file.createNewFile();}

程序运行将抛出:java.io.IOException: 系统找不到指定的路径。因为mkdir()方法没有成功创建多层目录。

建议使用:mkdirs()方法

0 0