FileUtils文件工具类详解

一、FileUtils概述

FileUtils是Apache Commons IO工具库的一部分,提供了许多封装好的静态方法来操作文件和文件夹,减少了我们手动实现的复杂度。通过使用FileUtils,我们可以方便地复制、移动、删除、重命名文件,以及追加/替换文件内容等操作。

二、FileUtils的安装

安装FileUtils十分简单,只需要将commons-io包导入项目的classpath中即可。Maven依赖如下:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>

三、FileUtils的使用

1、读取文件

我们可以使用FileUtils.readFileToString()方法从文件中读取字符串,该方法可以指定文件的编码方式。在方法调用失败时抛出异常。

    public static String readFileToString(File file, String encoding) throws IOException {
        return readLines(file, encoding).toString();
    }

实例:

    File file = new File("file.txt");
    String content = FileUtils.readFileToString(file, "UTF-8");
    System.out.println(content);

2、写入文件

我们可以使用FileUtils.write()方法将字符或字符串写入到文件中,该方法会自动创建文件以及相关的目录。如果你想使用追加模式将数据写入现有文件,则可以使用FileUtils.write()方法,并将第三个参数设置为true。

    public static void write(File file, CharSequence data, Charset encoding, boolean append) throws IOException {
        String str = data == null? null: data.toString();     
        writeStringToFile(file, str, encoding, append);
    }

实例:

    String content = "Hello, World!";
    File file = new File("file.txt");
    FileUtils.write(file, content, "UTF-8", false);
    // 追加模式
    FileUtils.write(file,content,"UTF-8",true);

3、复制文件

我们可以使用FileUtils.copyFile()方法复制文件。如果文件已经存在,则其被覆盖。如果源文件和目标文件是同一个文件,则不执行任何操作并返回。

    public static void copyFile(File srcFile, File destFile) throws IOException {
        if (srcFile == null) {
            throw new IllegalArgumentException("Source must not be null");
        }
        if (destFile == null) {
            throw new IllegalArgumentException("Destination must not be null");
        }
        if (!srcFile.exists()) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' exists but is a directory");
        }
        if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
            throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
        }
        copyFile(srcFile, destFile, true);
    }

实例:

    File srcFile = new File("src/file.txt");
    File destFile = new File("dest/file.txt");
    FileUtils.copyFile(srcFile,destFile); 

4、移动文件

我们可以使用FileUtils.moveFile()方法将文件移动到新位置。如果目标文件存在,则源文件将覆盖其内容。如果源文件和目标文件是同一个文件,则不执行任何操作并返回。

    public static void moveFile(File srcFile, File destFile) throws IOException {
        if (srcFile == null) {
            throw new IllegalArgumentException("Source must not be null");
        }
        if (destFile == null) {
            throw new IllegalArgumentException("Destination must not be null");
        }
        if (!srcFile.exists()) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (srcFile.isDirectory()) {
            throw new IOException("Source '" + srcFile + "' is a directory");
        }
        if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
            throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
        }
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' is a directory");
        }
        if (destFile.exists()) {
            if (!destFile.canWrite()) {
                throw new IOException("Destination '" + destFile + "' is read-only");
            }
            if (!confirmOverwrite(destFile)) {
                return;
            }
        } else {
            File parentDir = destFile.getParentFile();
            if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
                throw new IOException("Destination '" + parentDir + "' directory cannot be created");
            }
        }
        if (!srcFile.renameTo(destFile)) {
            copyFile(srcFile, destFile);
            if (!srcFile.delete()) {
                FileUtils.deleteQuietly(destFile);
                throw new IOException("Failed to delete original file '" + srcFile + "' after copy to '" + destFile + "'");
            }
        }
    }

实例:

    File srcFile = new File("src/file.txt");
    File destFile = new File("dest/file.txt");
    FileUtils.moveFile(srcFile,destFile); 

5、删除文件

我们可以使用FileUtils.delete()方法删除文件或目录以及其所有子目录。该方法递归地删除目录中的所有子目录和文件。如果删除失败,则在方法结束时抛出异常。

    public static void delete(File file) throws IOException {
        if (file.isDirectory()) {
            cleanDirectory(file);
        }
        if (!file.delete()) {
            throw new IOException("Unable to delete file: " + file);
        }
    }

实例:

    File file = new File("file.txt");
    FileUtils.deleteQuietly(file);

四、总结

通过本篇文章的介绍,我们了解了FileUtils的概述,安装步骤以及常用方法的使用。使用FileUtils,我们可以方便地处理文件和目录操作,减少了手动实现的复杂度,使得编程变得更加高效、简单。

转自:FileUtils文件工具类详解_笔记大全_设计学院

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java后端开发中,可以使用Java自带的工具类来处理压缩文件。其中,java.util.zip包提供了ZipOutputStream类,专门用于对文件进行压缩操作。通过使用ZipOutputStream类,我们可以将文件文件夹压缩成一个zip文件。 使用ZipOutputStream类进行压缩文件的操作步骤如下: 1. 创建一个ZipOutputStream对象,指定要输出的文件流。 2. 使用putNextEntry方法创建一个新的ZipEntry对象,指定要压缩的文件文件夹的路径。 3. 使用BufferedInputStream读取要压缩的文件文件夹的内容,并使用ZipOutputStream的write方法将内容写入压缩文件。 4. 循环执行步骤2和步骤3,直到所有要压缩的文件文件夹都被处理完毕。 5. 关闭ZipOutputStream对象,完成压缩操作。 下面是一个示例代码,展示了如何使用Java的ZipOutputStream类进行文件压缩操作: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtils { public static void compressFile(String sourceFilePath, String zipFilePath) throws IOException { File sourceFile = new File(sourceFilePath); FileOutputStream fos = new FileOutputStream(zipFilePath); ZipOutputStream zos = new ZipOutputStream(fos); compress(sourceFile, zos, ""); zos.close(); fos.close(); } private static void compress(File file, ZipOutputStream zos, String parentPath) throws IOException { if (file.isDirectory()) { // 如果是文件夹,则递归处理子文件夹和文件 File[] files = file.listFiles(); for (File subFile : files) { compress(subFile, zos, parentPath + file.getName() + "/"); } } else { // 如果是文件,则压缩文件 FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值