Java文件操作常用工具类

1. 引言

在 Java 开发中,经常需要对文件进行读取、写入、复制、删除等操作。为了简化这些操作,提高开发效率,我们可以使用一个常用的文件操作工具类。本文将介绍一个常用的 Java 文件操作工具类,并提供详细的使用说明和示例。

2. 工具类介绍

工具类的名称:FileUtil

工具类的功能:提供文件相关的操作方法,包括文件读取、写入、复制、删除等。

3. 工具类示例及使用说明

以下是 FileUtil 工具类的代码示例:

import java.io.*;
import java.nio.file.*;
import java.util.List;

/**
 * 文件操作工具类,提供文件相关的操作方法
 */
public class FileUtil {

    /**
     * 读取文件内容
     *
     * @param filePath 文件路径
     * @return 文件内容
     * @throws IOException 如果读取文件失败
     */
    public static String readFile(String filePath) throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }
        }
        return content.toString();
    }

    /**
     * 写入文件内容
     *
     * @param filePath 文件路径
     * @param content  写入的内容
     * @throws IOException 如果写入文件失败
     */
    public static void writeFile(String filePath, String content) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(content);
        }
    }

    /**
     * 复制文件
     *
     * @param sourceFilePath 源文件路径
     * @param destFilePath   目标文件路径
     * @throws IOException 如果复制文件失败
     */
    public static void copyFile(String sourceFilePath, String destFilePath) throws IOException {
        Path source = Paths.get(sourceFilePath);
        Path dest = Paths.get(destFilePath);
        Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     * @throws IOException 如果删除文件失败
     */
    public static void deleteFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        Files.deleteIfExists(path);
    }

    /**
     * 获取文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小,单位为字节
     * @throws IOException 如果获取文件大小失败
     */
    public static long getFileSize(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return Files.size(path);
    }

    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return true 如果文件存在;false 如果文件不存在
     */
    public static boolean fileExists(String filePath) {
        Path path = Paths.get(filePath);
        return Files.exists(path);
    }

    /**
     * 创建目录
     *
     * @param directoryPath 目录路径
    

 * @throws IOException 如果创建目录失败
     */
    public static void createDirectory(String directoryPath) throws IOException {
        Path path = Paths.get(directoryPath);
        Files.createDirectories(path);
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 文件扩展名
     */
    public static String getFileExtension(String fileName) {
        if (StringUtil.isEmpty(fileName)) {
            return "";
        }
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1);
        }
        return "";
    }

    /**
     * 获取文件行数
     *
     * @param filePath 文件路径
     * @return 文件行数
     * @throws IOException 如果读取文件失败
     */
    public static int getFileLineCount(String filePath) throws IOException {
        int count = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            while (reader.readLine() != null) {
                count++;
            }
        }
        return count;
    }

    /**
     * 获取文件列表
     *
     * @param directoryPath 目录路径
     * @return 文件列表
     * @throws IOException 如果读取目录失败
     */
    public static List<String> getFileList(String directoryPath) throws IOException {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directoryPath))) {
            List<String> fileList = new ArrayList<>();
            for (Path path : directoryStream) {
                if (Files.isRegularFile(path)) {
                    fileList.add(path.getFileName().toString());
                }
            }
            return fileList;
        }
    }

    /**
     * 重命名文件
     *
     * @param filePath    文件路径
     * @param newFileName 新文件名
     * @throws IOException 如果重命名文件失败
     */
    public static void renameFile(String filePath, String newFileName) throws IOException {
        Path source = Paths.get(filePath);
        Path target = source.resolveSibling(newFileName);
        Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
    }
}

在上述代码中,我们提供了常用的文件操作方法,包括:

  • readFile(String filePath):读取文件内容。
  • writeFile(String filePath, String content):写入文件内容。
  • copyFile(String sourceFilePath, String destFilePath):复制文件。
  • deleteFile(String filePath):删除文件。
  • getFileSize(String filePath):获取文件大小。
  • fileExists(String filePath):判断文件是否存在。
  • createDirectory(String directoryPath):创建目录。
  • getFileExtension(String fileName):获取文件扩展名。
  • getFileLineCount(String filePath):获取文件行数。
  • getFileList(String directoryPath):获取文件列表。
  • renameFile(String filePath, String newFileName):重命名文件。

4. 结论

本文介绍了一个常用的 Java 文件操作工具类 FileUtil,并提供了详细的使用说明和示例代码。这个工具类提供了丰富的文件操作方法,方便开发者处理文件的读取、写入、复制、删除等任务。使用这些工具类可以提高开发效率和代码可读性。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值