FileUtils案例

wen java案例 2

我来为您提供一个完整的FileUtils工具类的案例,包含文件操作的常见功能:

FileUtils案例

FileUtils工具类完整案例

基础文件操作

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
public class FileUtils {
    /**
     * 读取文件内容为字符串
     */
    public static String readFileToString(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)));
    }
    /**
     * 读取文件内容为字符串(指定编码)
     */
    public static String readFileToString(String filePath, Charset charset) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)), charset);
    }
    /**
     * 读取文件所有行
     */
    public static List<String> readLines(String filePath) throws IOException {
        return Files.readAllLines(Paths.get(filePath));
    }
    /**
     * 写入字符串到文件
     */
    public static void writeStringToFile(String filePath, String content) throws IOException {
        Files.write(Paths.get(filePath), content.getBytes());
    }
    /**
     * 追加字符串到文件
     */
    public static void appendStringToFile(String filePath, String content) throws IOException {
        Files.write(Paths.get(filePath), content.getBytes(), 
                StandardOpenOption.APPEND, StandardOpenOption.CREATE);
    }
}

文件复制、移动和删除

public class FileCopyMoveUtils {
    /**
     * 复制文件
     */
    public static void copyFile(String sourcePath, String destPath) throws IOException {
        Path source = Paths.get(sourcePath);
        Path dest = Paths.get(destPath);
        Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
    }
    /**
     * 移动文件
     */
    public static void moveFile(String sourcePath, String destPath) throws IOException {
        Path source = Paths.get(sourcePath);
        Path dest = Paths.get(destPath);
        Files.move(source, dest, StandardCopyOption.REPLACE_EXISTING);
    }
    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath) throws IOException {
        return Files.deleteIfExists(Paths.get(filePath));
    }
    /**
     * 递归删除目录及其内容
     */
    public static void deleteDirectory(File directory) throws IOException {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            directory.delete();
        }
    }
    /**
     * 复制目录及其内容
     */
    public static void copyDirectory(File sourceDir, File destDir) throws IOException {
        if (!sourceDir.exists() || !sourceDir.isDirectory()) {
            throw new IOException("源目录不存在");
        }
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                File destFile = new File(destDir, file.getName());
                if (file.isDirectory()) {
                    copyDirectory(file, destFile);
                } else {
                    copyFile(file.getAbsolutePath(), destFile.getAbsolutePath());
                }
            }
        }
    }
}

文件搜索和过滤

import java.util.ArrayList;
import java.util.List;
public class FileSearchUtils {
    /**
     * 查找指定扩展名的文件
     */
    public static List<File> findFilesByExtension(File directory, String extension) {
        List<File> result = new ArrayList<>();
        if (!directory.exists() || !directory.isDirectory()) {
            return result;
        }
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    result.addAll(findFilesByExtension(file, extension));
                } else if (file.getName().endsWith(extension)) {
                    result.add(file);
                }
            }
        }
        return result;
    }
    /**
     * 根据文件名关键字搜索文件
     */
    public static List<File> findFilesByName(File directory, String keyword) {
        List<File> result = new ArrayList<>();
        if (!directory.exists() || !directory.isDirectory()) {
            return result;
        }
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    result.addAll(findFilesByName(file, keyword));
                } else if (file.getName().contains(keyword)) {
                    result.add(file);
                }
            }
        }
        return result;
    }
    /**
     * 获取目录下所有文件(递归)
     */
    public static List<File> getAllFiles(File directory) {
        List<File> result = new ArrayList<>();
        if (!directory.exists() || !directory.isDirectory()) {
            return result;
        }
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    result.addAll(getAllFiles(file));
                } else {
                    result.add(file);
                }
            }
        }
        return result;
    }
}

文件比较和校验

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileCompareUtils {
    /**
     * 计算文件的MD5值
     */
    public static String getMD5(File file) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        return bytesToHex(digest);
    }
    /**
     * 计算文件的SHA-256值
     */
    public static String getSHA256(File file) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        try (InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        return bytesToHex(digest);
    }
    /**
     * 比较两个文件是否相同
     */
    public static boolean filesAreEqual(File file1, File file2) throws IOException, NoSuchAlgorithmException {
        if (file1.length() != file2.length()) {
            return false;
        }
        return getMD5(file1).equals(getMD5(file2));
    }
    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }
}

使用示例

public class FileUtilsDemo {
    public static void main(String[] args) {
        try {
            // 1. 写入文件
            FileUtils.writeStringToFile("test.txt", "Hello, World!");
            // 2. 追加内容
            FileUtils.appendStringToFile("test.txt", "\nThis is appended text.");
            // 3. 读取文件
            String content = FileUtils.readFileToString("test.txt");
            System.out.println("文件内容: " + content);
            // 4. 复制文件
            FileCopyMoveUtils.copyFile("test.txt", "copy.txt");
            System.out.println("文件复制成功");
            // 5. 移动文件
            FileCopyMoveUtils.moveFile("copy.txt", "moved.txt");
            System.out.println("文件移动成功");
            // 6. 查找文件
            File directory = new File(".");
            List<File> txtFiles = FileSearchUtils.findFilesByExtension(directory, ".txt");
            System.out.println("找到的txt文件: " + txtFiles.size() + " 个");
            // 7. 计算MD5
            File testFile = new File("test.txt");
            String md5 = FileCompareUtils.getMD5(testFile);
            System.out.println("文件的MD5值: " + md5);
            // 8. 删除文件
            FileCopyMoveUtils.deleteFile("moved.txt");
            System.out.println("文件删除成功");
            // 9. 读取所有行
            List<String> lines = FileUtils.readLines("test.txt");
            lines.forEach(System.out::println);
            // 清理
            FileCopyMoveUtils.deleteFile("test.txt");
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

高级功能示例

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class AdvancedFileUtils {
    /**
     * 保存对象到文件(使用ObjectOutputStream)
     */
    public static void saveObjectToFile(Object object, String filePath) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(object);
        }
    }
    /**
     * 从文件读取对象
     */
    public static Object readObjectFromFile(String filePath) throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            return ois.readObject();
        }
    }
    /**
     * 缓存文件内容带过期时间
     */
    public static class CachedFile {
        private String content;
        private LocalDate cacheDate;
        private final String filePath;
        public CachedFile(String filePath) {
            this.filePath = filePath;
        }
        public String getContent() throws IOException {
            if (content == null || !isCacheValid()) {
                content = FileUtils.readFileToString(filePath);
                cacheDate = LocalDate.now();
            }
            return content;
        }
        private boolean isCacheValid() {
            if (cacheDate == null) return false;
            return cacheDate.plusDays(1).isAfter(LocalDate.now());
        }
    }
    /**
     * 文件统计信息
     */
    public static class FileStats {
        public static void printStats(File file) {
            System.out.println("文件路径: " + file.getAbsolutePath());
            System.out.println("文件大小: " + formatSize(file.length()));
            System.out.println("最后修改时间: " + new java.util.Date(file.lastModified()));
            System.out.println("是否可读: " + file.canRead());
            System.out.println("是否可写: " + file.canWrite());
            System.out.println("是否目录: " + file.isDirectory());
        }
        private static String formatSize(long bytes) {
            if (bytes < 1024) return bytes + " B";
            int exp = (int) (Math.log(bytes) / Math.log(1024));
            String pre = "KMGTPE".charAt(exp - 1) + "";
            return String.format("%.2f %sB", bytes / Math.pow(1024, exp), pre);
        }
    }
}

这个FileUtils工具类提供了文件操作中最常用的功能,包括:

  • 读写文件
  • 复制、移动、删除
  • 搜索、过滤
  • 比较、校验
  • 序列化
  • 缓存
  • 统计信息

您可以根据实际需求选择相应的功能使用。

上一篇HttpUtils案例

下一篇DateUtils案例

抱歉,评论功能暂时关闭!