You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PAIR/src/main/java/com/mathquiz/util/FileUtils.java

111 lines
3.2 KiB

package com.util;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
/**
* 文件操作工具类
* 提供文件读写、目录创建等常用操作
*/
public class FileUtils {
/**
* 读取文件内容为字符串
* @param filePath 文件路径
* @return 文件内容
* @throws IOException 读取失败时抛出
*/
public static String readFileToString(String filePath) throws IOException {
return Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
}
/**
* 写入字符串到文件
* @param filePath 文件路径
* @param content 要写入的内容
* @throws IOException 写入失败时抛出
*/
public static void writeStringToFile(String filePath, String content) throws IOException {
Files.writeString(Paths.get(filePath), content, StandardCharsets.UTF_8);
}
/**
* 创建目录(如果不存在)
* @param dirPath 目录路径
* @throws IOException 创建失败时抛出
*/
public static void createDirectoryIfNotExists(String dirPath) throws IOException {
Path path = Paths.get(dirPath);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
}
/**
* 检查文件是否存在
* @param filePath 文件路径
* @return true表示存在
*/
public static boolean exists(String filePath) {
return Files.exists(Paths.get(filePath));
}
/**
* 删除文件
* @param filePath 文件路径
* @return true表示删除成功
*/
public static boolean deleteFile(String filePath) {
try {
return Files.deleteIfExists(Paths.get(filePath));
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取目录下所有文件
* @param dirPath 目录路径
* @return 文件数组
*/
public static File[] listFiles(String dirPath) {
File dir = new File(dirPath);
if (dir.exists() && dir.isDirectory()) {
return dir.listFiles();
}
return new File[0];
}
/**
* 追加内容到文件末尾
* @param filePath 文件路径
* @param content 要追加的内容
* @throws IOException 追加失败时抛出
*/
public static void appendToFile(String filePath, String content) throws IOException {
Files.writeString(Paths.get(filePath), content, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
/**
* 复制文件
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
* @throws IOException 复制失败时抛出
*/
public static void copyFile(String sourcePath, String targetPath) throws IOException {
Files.copy(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
}
/**
* 获取文件大小(字节)
* @param filePath 文件路径
* @return 文件大小
* @throws IOException 获取失败时抛出
*/
public static long getFileSize(String filePath) throws IOException {
return Files.size(Paths.get(filePath));
}
}