Skip to content

Java 文件管理 ​

核心知识点总结 ​

操作类别核心方法说明
路径操作getPath(), getAbsolutePath(), getCanonicalPath()获取不同格式的路径
文件信息getName(), length(), lastModified()获取文件属性
判断方法exists(), isFile(), isDirectory(), isHidden()判断文件状态
创建操作createNewFile(), mkdir(), mkdirs()创建文件和目录
删除操作delete()删除文件或空目录
重命名renameTo()移动或重命名
目录列表list(), listFiles()获取目录内容
过滤FilenameFilter过滤文件名
分隔符File.separator, File.pathSeparator跨平台路径分隔符

这套示例程序涵盖了 Java 文件管理的所有核心操作,可以作为学习和参考的完整教程。

一、基础概念示例 ​

1. 路径演示程序 ​

java
import java.io.File;
import java.io.IOException;

public class PathDemo {
    public static void main(String[] args) {
        System.out.println("========== 路径概念演示 ==========\n");
        
        // 1. 绝对路径示例
        System.out.println("【绝对路径】");
        File absoluteFile = new File("D:/JavaProjects/test.txt");
        System.out.println("路径: " + absoluteFile.getPath());
        System.out.println("绝对路径: " + absoluteFile.getAbsolutePath());
        
        // 2. 相对路径示例
        System.out.println("\n【相对路径】");
        File relativeFile = new File("data/config.txt");
        System.out.println("路径: " + relativeFile.getPath());
        System.out.println("绝对路径: " + relativeFile.getAbsolutePath());
        
        // 3. 当前工作目录
        System.out.println("\n【当前工作目录】");
        File currentDir = new File(".");
        System.out.println("当前目录: " + currentDir.getAbsolutePath());
        
        // 4. 父目录表示
        System.out.println("\n【父目录表示】");
        File parentFile = new File("../parent.txt");
        System.out.println("路径: " + parentFile.getPath());
        System.out.println("绝对路径: " + parentFile.getAbsolutePath());
        
        // 5. 不同操作系统的路径分隔符
        System.out.println("\n【系统路径分隔符】");
        System.out.println("路径分隔符: " + File.pathSeparator);
        System.out.println("路径分隔符字符: " + File.pathSeparatorChar);
        System.out.println("名称分隔符: " + File.separator);
        System.out.println("名称分隔符字符: " + File.separatorChar);
    }
}

2. 路径拼接示例 ​

java
import java.io.File;

public class PathConcatenationDemo {
    public static void main(String[] args) {
        System.out.println("========== 路径拼接演示 ==========\n");
        
        // 方法1:使用构造函数
        File baseDir = new File("D:/JavaProjects");
        File file1 = new File(baseDir, "src/Main.java");
        System.out.println("方法1: " + file1.getAbsolutePath());
        
        // 方法2:使用路径分隔符拼接
        String path2 = "D:" + File.separator + "JavaProjects" + File.separator + "bin";
        File file2 = new File(path2);
        System.out.println("方法2: " + file2.getAbsolutePath());
        
        // 方法3:使用构造函数
        File parent = new File("D:/JavaProjects/src");
        File file3 = new File(parent, "com/example/App.java");
        System.out.println("方法3: " + file3.getAbsolutePath());
        
        // 方法4:多级路径自动创建(需要手动创建目录)
        File complexPath = new File("D:/JavaProjects/src/main/java/com/example");
        System.out.println("方法4: " + complexPath.getAbsolutePath());
        
        // 方法5:使用相对路径和绝对路径混合
        File mixedPath = new File("D:/JavaProjects", "../config/settings.xml");
        System.out.println("方法5: " + mixedPath.getAbsolutePath());
        
        // 方法6:规范化路径(去除..和.)
        try {
            System.out.println("规范化路径: " + mixedPath.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、文件和目录的基本操作 ​

3. 完整的文件管理类 ​

java
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileOperationDemo {
    
    // 1. 创建文件
    public static boolean createFile(String filePath) {
        File file = new File(filePath);
        
        // 检查文件是否已存在
        if (file.exists()) {
            System.out.println("文件已存在: " + filePath);
            return false;
        }
        
        try {
            // 确保父目录存在
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();  // 创建父目录
                System.out.println("创建父目录: " + parentDir.getAbsolutePath());
            }
            
            // 创建文件
            boolean result = file.createNewFile();
            if (result) {
                System.out.println("文件创建成功: " + filePath);
            }
            return result;
        } catch (IOException e) {
            System.out.println("创建文件失败: " + e.getMessage());
            return false;
        }
    }
    
    // 2. 创建目录
    public static boolean createDirectory(String dirPath) {
        File dir = new File(dirPath);
        
        if (dir.exists()) {
            System.out.println("目录已存在: " + dirPath);
            return false;
        }
        
        // mkdir() - 创建单级目录,父目录必须存在
        // mkdirs() - 创建多级目录,自动创建不存在的父目录
        boolean result = dir.mkdirs();
        if (result) {
            System.out.println("目录创建成功: " + dirPath);
        } else {
            System.out.println("目录创建失败: " + dirPath);
        }
        return result;
    }
    
    // 3. 删除文件或目录
    public static boolean deleteFileOrDir(String path) {
        File file = new File(path);
        
        if (!file.exists()) {
            System.out.println("文件或目录不存在: " + path);
            return false;
        }
        
        // 如果是目录,递归删除所有内容
        if (file.isDirectory()) {
            deleteDirectoryRecursively(file);
        }
        
        boolean result = file.delete();
        if (result) {
            System.out.println("删除成功: " + path);
        } else {
            System.out.println("删除失败: " + path);
        }
        return result;
    }
    
    // 递归删除目录
    private static void deleteDirectoryRecursively(File dir) {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectoryRecursively(file);
                }
                file.delete();
            }
        }
    }
    
    // 4. 重命名文件或目录
    public static boolean rename(String oldPath, String newPath) {
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);
        
        if (!oldFile.exists()) {
            System.out.println("原文件不存在: " + oldPath);
            return false;
        }
        
        if (newFile.exists()) {
            System.out.println("目标文件已存在: " + newPath);
            return false;
        }
        
        boolean result = oldFile.renameTo(newFile);
        if (result) {
            System.out.println("重命名成功: " + oldPath + " -> " + newPath);
        } else {
            System.out.println("重命名失败");
        }
        return result;
    }
    
    // 5. 获取文件扩展名
    public static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex + 1);
        }
        return "";
    }
    
    // 6. 获取文件详细信息
    public static void printFileInfo(String filePath) {
        File file = new File(filePath);
        
        System.out.println("\n========== 文件信息 ==========");
        System.out.println("文件名: " + file.getName());
        System.out.println("扩展名: " + getFileExtension(file.getName()));
        System.out.println("路径: " + file.getPath());
        System.out.println("绝对路径: " + file.getAbsolutePath());
        
        try {
            System.out.println("规范路径: " + file.getCanonicalPath());
        } catch (IOException e) {
            System.out.println("获取规范路径失败: " + e.getMessage());
        }
        
        System.out.println("父路径: " + file.getParent());
        System.out.println("文件大小: " + formatFileSize(file.length()));
        System.out.println("最后修改: " + formatDate(file.lastModified()));
        
        System.out.println("是否存在: " + file.exists());
        System.out.println("是否是文件: " + file.isFile());
        System.out.println("是否是目录: " + file.isDirectory());
        System.out.println("是否隐藏: " + file.isHidden());
        System.out.println("是否绝对路径: " + file.isAbsolute());
        
        System.out.println("可读: " + file.canRead());
        System.out.println("可写: " + file.canWrite());
        System.out.println("可执行: " + file.canExecute());
        
        // 获取磁盘空间信息(Java 6+)
        System.out.println("\n磁盘空间信息:");
        System.out.println("总空间: " + formatFileSize(file.getTotalSpace()));
        System.out.println("可用空间: " + formatFileSize(file.getFreeSpace()));
        System.out.println("可分配空间: " + formatFileSize(file.getUsableSpace()));
    }
    
    // 格式化文件大小
    private static String formatFileSize(long size) {
        if (size < 1024) return size + " B";
        if (size < 1024 * 1024) return String.format("%.2f KB", size / 1024.0);
        if (size < 1024 * 1024 * 1024) return String.format("%.2f MB", size / (1024.0 * 1024));
        return String.format("%.2f GB", size / (1024.0 * 1024 * 1024));
    }
    
    // 格式化日期
    private static String formatDate(long timestamp) {
        if (timestamp <= 0) return "未知";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(timestamp));
    }
    
    // 判断文件是否存在
    public static boolean exists(String path) {
        File file = new File(path);
        return file.exists();
    }
    
    // 判断是否是文件
    public static boolean isFile(String path) {
        File file = new File(path);
        return file.exists() && file.isFile();
    }
    
    // 判断是否是目录
    public static boolean isDirectory(String path) {
        File file = new File(path);
        return file.exists() && file.isDirectory();
    }
}

三、目录遍历和文件列表 ​

4. 目录列表和过滤 ​

java
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;

public class DirectoryListingDemo {
    
    // 1. 列出目录内容(基本)
    public static void listDirectoryBasic(String dirPath) {
        File dir = new File(dirPath);
        
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("目录不存在: " + dirPath);
            return;
        }
        
        System.out.println("\n========== 目录内容: " + dirPath + " ==========");
        
        // 获取所有文件和目录名
        String[] names = dir.list();
        if (names != null) {
            System.out.println("共 " + names.length + " 个项目");
            for (String name : names) {
                File file = new File(dir, name);
                String type = file.isDirectory() ? "[目录]" : "[文件]";
                System.out.println(type + " " + name);
            }
        }
    }
    
    // 2. 详细列出目录内容(包括文件信息)
    public static void listDirectoryDetailed(String dirPath) {
        File dir = new File(dirPath);
        
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("目录不存在: " + dirPath);
            return;
        }
        
        System.out.println("\n========== 详细列表: " + dirPath + " ==========");
        
        File[] files = dir.listFiles();
        if (files != null) {
            // 按文件类型排序:目录在前,文件在后
            Arrays.sort(files, (f1, f2) -> {
                if (f1.isDirectory() && !f2.isDirectory()) return -1;
                if (!f1.isDirectory() && f2.isDirectory()) return 1;
                return f1.getName().compareToIgnoreCase(f2.getName());
            });
            
            long totalSize = 0;
            int dirCount = 0;
            int fileCount = 0;
            
            for (File file : files) {
                if (file.isDirectory()) {
                    dirCount++;
                    System.out.printf("[目录] %-30s %s\n", 
                        file.getName(), getFormattedDate(file.lastModified()));
                } else {
                    fileCount++;
                    totalSize += file.length();
                    System.out.printf("[文件] %-30s %10s  %s\n", 
                        file.getName(), 
                        formatFileSize(file.length()),
                        getFormattedDate(file.lastModified()));
                }
            }
            
            System.out.println("\n统计: " + dirCount + " 个目录, " + fileCount + " 个文件");
            System.out.println("总大小: " + formatFileSize(totalSize));
        }
    }
    
    // 3. 递归列出所有文件和子目录
    public static void listDirectoryRecursive(String dirPath, int level) {
        File dir = new File(dirPath);
        
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        
        File[] files = dir.listFiles();
        if (files == null) return;
        
        String indent = "  ".repeat(level);
        
        for (File file : files) {
            System.out.println(indent + "├─ " + file.getName() + 
                (file.isDirectory() ? "/" : " (" + formatFileSize(file.length()) + ")"));
            
            if (file.isDirectory()) {
                listDirectoryRecursive(file.getAbsolutePath(), level + 1);
            }
        }
    }
    
    // 4. 使用 FilenameFilter 过滤文件
    public static void filterFiles(String dirPath, String extension) {
        File dir = new File(dirPath);
        
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("目录不存在: " + dirPath);
            return;
        }
        
        // 创建过滤器
        FilenameFilter filter = (d, name) -> name.toLowerCase().endsWith(extension);
        
        String[] filteredNames = dir.list(filter);
        
        if (filteredNames != null && filteredNames.length > 0) {
            System.out.println("\n========== 过滤 *" + extension + " 文件 ==========");
            for (String name : filteredNames) {
                File file = new File(dir, name);
                System.out.println("  " + name + " (" + formatFileSize(file.length()) + ")");
            }
        } else {
            System.out.println("没有找到 *" + extension + " 文件");
        }
    }
    
    // 5. 搜索文件
    public static void searchFile(String dirPath, String fileName) {
        File dir = new File(dirPath);
        
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("目录不存在: " + dirPath);
            return;
        }
        
        System.out.println("\n========== 搜索文件: " + fileName + " ==========");
        searchFileRecursive(dir, fileName);
    }
    
    private static void searchFileRecursive(File dir, String fileName) {
        File[] files = dir.listFiles();
        if (files == null) return;
        
        for (File file : files) {
            if (file.isDirectory()) {
                searchFileRecursive(file, fileName);
            } else if (file.getName().equalsIgnoreCase(fileName)) {
                System.out.println("找到: " + file.getAbsolutePath());
                System.out.println("  大小: " + formatFileSize(file.length()));
                System.out.println("  修改: " + getFormattedDate(file.lastModified()));
            }
        }
    }
    
    // 辅助方法
    private static String formatFileSize(long size) {
        if (size < 1024) return size + "B";
        if (size < 1024 * 1024) return String.format("%.1fKB", size / 1024.0);
        if (size < 1024 * 1024 * 1024) return String.format("%.1fMB", size / (1024.0 * 1024));
        return String.format("%.2fGB", size / (1024.0 * 1024 * 1024));
    }
    
    private static String getFormattedDate(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(timestamp));
    }
}