PathUtils 工具类作用
PathUtils是一个Java路径操作工具类,其主要作用是提供一系列方便的方法来操作和处理文件路径。
应用场景包括:
-
文件路径的拼接:PathUtils可以提供方法来拼接多个文件路径,例如可以将文件名和文件夹路径拼接在一起。
-
文件路径的解析:PathUtils可以提供方法来解析文件路径,例如可以获取文件的名称、文件的父路径等信息。
-
文件路径的规范化:PathUtils可以提供方法来规范化文件路径,例如可以去除文件路径中的冗余信息、统一文件路径的格式等。
-
文件路径的判断:PathUtils可以提供方法来判断文件路径是否存在、是否为文件夹、是否为文件等。
-
文件路径的转换:PathUtils可以提供方法来转换不同操作系统下的文件路径格式,例如可以将Windows下的文件路径转换为Linux下的文件路径。
PathUtils 工具类实现
package com.example.utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
/**
* PathUtils 工具类
* 提供路径操作的常用方法
*/
public class PathUtils {
/**
* 获取当前工作目录
*
* @return 当前工作目录的路径
*/
public static String getCurrentWorkingDirectory() {
return System.getProperty("user.dir");
}
/**
* 获取用户主目录
*
* @return 用户主目录的路径
*/
public static String getUserHomeDirectory() {
return System.getProperty("user.home");
}
/**
* 拼接路径
*
* @param basePath 基础路径
* @param paths 要拼接的路径数组
* @return 拼接后的完整路径
*/
public static String joinPaths(String basePath, String... paths) {
Path path = Paths.get(basePath, paths);
return path.toString();
}
/**
* 检查路径是否存在
*
* @param path 要检查的路径
* @return 如果路径存在,返回 true;否则返回 false
*/
public static boolean exists(String path) {
return Files.exists(Paths.get(path));
}
/**
* 判断路径是否是文件
*
* @param path 要检查的路径
* @return 如果是文件,返回 true;否则返回 false
*/
public static boolean isFile(String path) {
return Files.isRegularFile(Paths.get(path));
}
/**
* 判断路径是否是目录
*
* @param path 要检查的路径
* @return 如果是目录,返回 true;否则返回 false
*/
public static boolean isDirectory(String path) {
return Files.isDirectory(Paths.get(path));
}
/**
* 创建文件
*
* @param path 文件路径
* @return 如果创建成功,返回 true;否则返回 false
* @throws IOException 文件创建失败时抛出异常
*/
public static boolean createFile(String path) throws IOException {
Path filePath = Paths.get(path);
if (exists(path)) {
return false;
}
Files.createFile(filePath);
return true;
}
/**
* 创建目录
*
* @param path 目录路径
* @return 如果创建成功,返回 true;否则返回 false
* @throws IOException 目录创建失败时抛出异常
*/
public static boolean createDirectory(String path) throws IOException {
Path dirPath = Paths.get(path);
if (exists(path)) {
return false;
}
Files.createDirectories(dirPath);
return true;
}
/**
* 删除文件或目录
*
* @param path 文件或目录的路径
* @return 如果删除成功,返回 true;否则返回 false
* @throws IOException 删除失败时抛出异常
*/
public static boolean delete(String path) throws IOException {
Path targetPath = Paths.get(path);
if (!exists(path)) {
return false;
}
if (isDirectory(path)) {
Files.walkFileTree(targetPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.delete(targetPath);
}
return true;
}
/**
* 列出目录中的所有文件和子目录
*
* @param path 目录路径
* @return 包含所有文件和子目录路径的列表
* @throws IOException 读取目录失败时抛出异常
*/
public static List<String> listDirectory(String path) throws IOException {
List<String> fileList = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path))) {
for (Path entry : stream) {
fileList.add(entry.toString());
}
}
return fileList;
}
/**
* 读取文件内容
*
* @param path 文件路径
* @return 文件内容的字符串
* @throws IOException 读取文件失败时抛出异常
*/
public static String readFile(String path) throws IOException {
return new String(Files.readAllBytes(Paths.get(path)));
}
/**
* 写入内容到文件
*
* @param path 文件路径
* @param content 要写入的内容
* @param append 是否追加内容
* @throws IOException 写入文件失败时抛出异常
*/
public static void writeFile(String path, String content, boolean append) throws IOException {
Path filePath = Paths.get(path);
if (append) {
Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} else {
Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
}
/**
* 复制文件或目录
*
* @param sourcePath 源路径
* @param targetPath 目标路径
* @throws IOException 复制失败时抛出异常
*/
public static void copy(String sourcePath, String targetPath) throws IOException {
Path source = Paths.get(sourcePath);
Path target = Paths.get(targetPath);
if (isDirectory(sourcePath)) {
Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Files.createDirectories(target.resolve(source.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
}
/**
* 移动文件或目录
*
* @param sourcePath 源路径
* @param targetPath 目标路径
* @throws IOException 移动失败时抛出异常
*/
public static void move(String sourcePath, String targetPath) throws IOException {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
}
/**
* 获取文件的扩展名
*
* @param path 文件路径
* @return 文件扩展名
*/
public static String getFileExtension(String path) {
String fileName = Paths.get(path).getFileName().toString();
int lastDotIndex = fileName.lastIndexOf('.');
return (lastDotIndex == -1) ? "" : fileName.substring(lastDotIndex + 1);
}
/**
* 获取文件的名称(不含扩展名)
*
* @param path 文件路径
* @return 文件名称
*/
public static String getFileNameWithoutExtension(String path) {
String fileName = Paths.get(path).getFileName().toString();
int lastDotIndex = fileName.lastIndexOf('.');
return (lastDotIndex == -1) ? fileName : fileName.substring(0, lastDotIndex);
}
}
主要功能简介
-
路径获取:
getCurrentWorkingDirectory
:获取当前工作目录的路径。getUserHomeDirectory
:获取用户主目录的路径。
-
路径拼接:
joinPaths
:将多个路径拼接成一个完整路径。
-
路径检查:
exists
:检查路径是否存在。isFile
:判断路径是否是文件。isDirectory
:判断路径是否是目录。
-
文件和目录操作:
createFile
:创建文件。createDirectory
:创建目录。delete
:删除文件或目录,支持递归删除目录及其内容。listDirectory
:列出目录中的所有文件和子目录。
-
文件读写:
readFile
:读取文件内容为字符串。writeFile
:将内容写入文件,支持追加模式和覆盖模式。
-
文件和目录复制移动:
copy
:复制文件或目录,支持递归复制目录及其内容。move
:移动文件或目录到新位置。
-
文件名和扩展名操作:
getFileExtension
:获取文件的扩展名。
getFileNameWithoutExtension
:获取文件名,不含扩展名。
使用示例
import com.example.utils.PathUtils;
import java.io.IOException;
import java.util.List;
public class PathUtilsTest {
public static void main(String[] args) {
String testDir = PathUtils.joinPaths(PathUtils.getCurrentWorkingDirectory(), "testDir");
String testFile = PathUtils.joinPaths(testDir, "testFile.txt");
try {
// 创建目录
if (PathUtils.createDirectory(testDir)) {
System.out.println("Directory created: " + testDir);
} else {
System.out.println("Directory already exists: " + testDir);
}
// 创建文件
if (PathUtils.createFile(testFile)) {
System.out.println("File created: " + testFile);
} else {
System.out.println("File already exists: " + testFile);
}
// 写入文件
PathUtils.writeFile(testFile, "Hello, World!", false);
System.out.println("Content written to file.");
// 读取文件
String content = PathUtils.readFile(testFile);
System.out.println("Read content from file: " + content);
// 列出目录内容
List<String> fileList = PathUtils.listDirectory(testDir);
System.out.println("Files in directory: " + fileList);
// 获取文件扩展名和名称
System.out.println("File extension: " + PathUtils.getFileExtension(testFile));
System.out.println("File name without extension: " + PathUtils.getFileNameWithoutExtension(testFile));
// 删除文件
if (PathUtils.delete(testFile)) {
System.out.println("File deleted: " + testFile);
}
// 删除目录
if (PathUtils.delete(testDir)) {
System.out.println("Directory deleted: " + testDir);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
结论
PathUtils
工具类通过封装 Java NIO 提供的路径和文件操作功能,简化了路径的获取、拼接、检查以及文件和目录的创建、删除、读写等操作。该工具类提高了代码的可读性和开发效率,特别适合用于处理文件系统路径的各种场景。无论是路径的拼接、文件的读写、目录的管理还是路径的各种检查和操作,PathUtils
都提供了简单易用的接口,使得路径操作变得更加便捷。
总结
PathUtils是一个Java路径操作工具类,用于处理文件路径的常见操作。它提供了一些静态方法,帮助开发人员简化路径操作的复杂度。
该工具类的主要功能包括:
-
获取路径的扩展名:提供了一个静态方法
getExtension
,用于从路径中获取文件的扩展名。例如,如果给定路径为“/path/to/file.txt”,则该方法将返回“txt”。 -
拼接路径:提供了一个静态方法
concat
,用于拼接多个路径片段。它会自动处理路径分隔符,确保生成的路径是正确的。例如,如果给定的路径片段为“/path/to”和“file.txt”,则该方法将返回“/path/to/file.txt”。 -
规范化路径:提供了一个静态方法
normalize
,用于规范化路径。它会移除路径中多余的分隔符,并处理“.”和“…”等特殊符号。例如,如果给定的路径为“/path/./to/…/file.txt”,则该方法将返回“/path/file.txt”。 -
获取文件名:提供了一个静态方法
getFileName
,用于从路径中提取文件名(包括扩展名)。例如,如果给定的路径为“/path/to/file.txt”,则该方法将返回“file.txt”。 -
获取文件所在目录:提供了一个静态方法
getParentDirectory
,用于从路径中获取文件所在的目录。例如,如果给定的路径为“/path/to/file.txt”,则该方法将返回“/path/to”。