1. Related libraries
The related class libraries established for directories and files in Java are all File, which is equivalent to unified modeling, but to be honest, it is almost the same, just treat the directory as a special file.
Common directory operations are nothing more than adding, deleting, renaming, and querying subdirectories. We write a tool class.
2. Directory operation tools
code show as below:
/**
1. 目录操作工具类
*/
public class DirectoryUtils {
/**
* 创建目录
*/
public static boolean createDirectory(String path) {
File dir = new File(path);
return dir.mkdir();
}
/**
* 删除目录
*/
public static boolean deleteDirectory(String path) {
File dir = new File(path);
return dir.delete();
}
/**
* 重命名目录
*/
public static boolean renameDirectory(String oldPath, String newPath) {
File dir = new File(oldPath);
return dir.renameTo(new File(newPath));
}
/**
* 列出子目录信息
*/
public static File[] getChildrenDirectories(String path) {
File dir = new File(path);
return dir.listFiles();
}
/**
* 测试
*/
public static void main(String[] args) throws IOException, InterruptedException {
// 新增目录测试
DirectoryUtils.createDirectory("D:/dir");
DirectoryUtils.createDirectory("D:/dir/dir1");
DirectoryUtils.createDirectory("D:/dir/dir2");
DirectoryUtils.createDirectory("D:/dir/dir3");
// 重命名测试
DirectoryUtils.renameDirectory("D:/dir/dir1", "D:/dir/dir_1");
DirectoryUtils.renameDirectory("D:/dir/dir2", "D:/dir/dir_2");
// 删除测试
DirectoryUtils.deleteDirectory("D:/dir/dir3");
// 列出子目录
File[] files = DirectoryUtils.getChildrenDirectories("D:/dir");
for (File file : files) {
System.out.println(file.getName());
}
}
}
3. Code explanation
There are several points to note:
- If the parent directory does not exist, the direct creation of the subdirectory will return false, for example, if it does not exist
D:/dir
, the direct creationD:/dir/dir1
will fail. - Can be used
/
as a platform-independent path separator, directly on platforms such as Windows - It can also be used
\\
as a path style character on the Windows platform, where the first backslash is an escape character.