linux file.getParentFile().mkdirs() 报错
时间: 2024-05-24 21:11:33 浏览: 16
这个错误通常是因为在Linux系统中,父目录的权限不足导致的。具体的解决方法是:
1. 使用root用户或者有足够权限的用户进行操作。
2. 修改父目录的权限,使当前用户有足够的权限进行操作。可以使用chmod命令修改权限。
3. 如果父目录不存在,可以使用mkdir -p命令创建所有不存在的父目录。
相关问题
除了使用file.getParentFile().mkdirs() ,其他方法
1. 使用Apache Commons IO库的FileUtils.forceMkdir()方法。这个方法会创建所有不存在的父目录。
2. 使用Java 7引入的Files.createDirectories()方法。这个方法也会创建所有不存在的父目录。
3. 使用Java 7引入的Path.getParent()方法获取父路径,然后使用Files.createDirectories()方法创建所有不存在的父目录。
4. 使用Guava库的Files.createParentDirs()方法。这个方法会创建所有不存在的父目录。
5. 使用自定义的递归方法创建所有不存在的父目录。例如:
```java
public static boolean createParentDirectories(File file) {
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) {
if (!createParentDirectories(parentFile)) {
return false;
}
if (!parentFile.mkdir()) {
return false;
}
}
return true;
}
```
File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc;将这两个if语句合并
可以将这两个if语句合并为一个if语句,如下所示:
```
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.exists() && !desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return desc;
```
这里使用了逻辑运算符&&,表示只有在desc不存在且其父目录也不存在时,才创建其父目录。如果desc或其父目录已经存在,则不会执行mkdirs()方法。这种方式可以使代码更加简洁易读。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)