Java 在给定路径上创建文件,所在文件夹不存在时,如何正确创建。

/**
* 创建多级目录文件
*
* @param path 文件路径
* @throws IOException
*/
private void createFile(String path) throws IOException {
if (StringUtils.isNotEmpty(path)) {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
}
        </div>

第二种方法代码如下:

//路径
String path = "/usr/sunny/images/product/img/";
File file = new File(path);
//如果路径不存在,新建
if(!file.exists()&&!file.isDirectory()) {
    file.mkdirs();
}
原文地址:https://www.cnblogs.com/jpfss/p/8867266.html