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,我们可以方便地处理文件和目录操作,减少了手动实现的复杂度,使得编程变得更加高效、简单。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/186244.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-11-27 05:45
下一篇 2024-11-27 05:45

相关推荐

  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常问题的解决

    本文旨在解决vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常的问题,提供完整的代码示例供参考。 一、分析问题 首先,需了解vue中下载文件的情况。一般情况下,我们…

    编程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件并生成完整的图像

    OBJ格式是一种用于表示3D对象的标准格式,通常由一组顶点、面和纹理映射坐标组成。在本文中,我们将讨论如何将多个OBJ文件拼接在一起,生成一个完整的3D模型。 一、读取OBJ文件 …

    编程 2025-04-29
  • Python中读入csv文件数据的方法用法介绍

    csv是一种常见的数据格式,通常用于存储小型数据集。Python作为一种广泛流行的编程语言,内置了许多操作csv文件的库。本文将从多个方面详细介绍Python读入csv文件的方法。…

    编程 2025-04-29
  • Python程序文件的拓展

    Python是一门功能丰富、易于学习、可读性高的编程语言。Python程序文件通常以.py为文件拓展名,被广泛应用于各种领域,包括Web开发、机器学习、科学计算等。为了更好地发挥P…

    编程 2025-04-29
  • 为什么用cmd运行Java时需要在文件内打开cmd为中心

    在Java开发中,我们经常会使用cmd在命令行窗口运行程序。然而,有时候我们会发现,在运行Java程序时,需要在文件内打开cmd为中心,这让很多开发者感到疑惑,那么,为什么会出现这…

    编程 2025-04-29
  • Python将矩阵存为CSV文件

    CSV文件是一种通用的文件格式,在统计学和计算机科学中非常常见,一些数据分析工具如Microsoft Excel,Google Sheets等都支持读取CSV文件。Python内置…

    编程 2025-04-29
  • Python zipfile解压文件乱码处理

    本文主要介绍如何在Python中使用zipfile进行文件解压的处理,同时详细讨论在解压文件时可能出现的乱码问题的各种解决办法。 一、zipfile解压文件乱码问题的根本原因 在P…

    编程 2025-04-29
  • Python如何导入py文件

    Python是一种开源的高级编程语言,因其易学易用和强大的生态系统而备受青睐。Python的import语句可以帮助用户将一个模块中的代码导入到另一个模块中,从而实现代码的重用。本…

    编程 2025-04-29
  • Python合并多个相同表头文件

    对于需要合并多个相同表头文件的情况,我们可以使用Python来实现快速的合并。 一、读取CSV文件 使用Python中的csv库读取CSV文件。 import csv with o…

    编程 2025-04-29

发表回复

登录后才能评论