Apache Commons IO – Apache Commons IO

最后修改: 2017年 9月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The Apache Commons project was created to provide developers with a set of common libraries that they can use in their day-to-day code.

创建Apache Commons项目是为了向开发者提供一套他们可以在日常代码中使用的通用库。

In this tutorial, we’ll explore some of the key utility classes of the Commons IO module and their most well-known functions.

在本教程中,我们将探讨Commons IO模块的一些关键实用类和它们最著名的功能。

2. Maven Dependency

2.Maven的依赖性

To use the library, let’s include the following Maven dependency in the pom.xml:

为了使用该库,我们在pom.xml中加入以下Maven依赖项。

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

The latest versions of the library can be found in Maven Central.

该库的最新版本可在Maven中心找到。

3. Utility Classes

3.实用类

Simply put, utility classes provide sets of static methods that can be used to perform common tasks on files.

简单地说,实用类提供了一组静态方法,可用于对文件执行常见任务

3.1. FileUtils

<3.1. FileUtils

This class provides different operations on files, such as opening, reading, copying, and moving.

该类提供对文件的不同操作,如打开、读取、复制和移动。

Let’s look at how to read or copy files using FileUtils:

让我们看看如何使用FileUtils读取或复制文件

File file = FileUtils.getFile(getClass().getClassLoader()
  .getResource("fileTest.txt")
  .getPath());
File tempDir = FileUtils.getTempDirectory();
FileUtils.copyFileToDirectory(file, tempDir);
File newTempFile = FileUtils.getFile(tempDir, file.getName());
String data = FileUtils.readFileToString(newTempFile,
  Charset.defaultCharset());

3.2. FilenameUtils

3.2.FilenameUtils

This utility provides an operating-system-agnostic way of executing common functions on file names. Let’s see some of the different methods we can utilize:

这个工具提供了一种与操作系统无关的方式来执行文件名上的普通函数。让我们看看我们可以利用的一些不同方法。

String fullPath = FilenameUtils.getFullPath(path);
String extension = FilenameUtils.getExtension(path);
String baseName = FilenameUtils.getBaseName(path);

3.3. FileSystemUtils

3.3.FileSystemUtils

We can use FileSystemUtils to check the free space on a given volume or drive:

我们可以使用FileSystemUtils检查特定卷或驱动器上的可用空间

long freeSpace = FileSystemUtils.freeSpaceKb("/");

4. Input and Output

4.输入和输出

This package provides several implementations for working with input and output streams.

这个包提供了几个实现,用于处理输入和输出流

We’ll focus on TeeInputStream and TeeOutputSteam. The word “Tee” (derived from letter “T“) is normally used to describe that a single input is to be split into two different outputs.

我们将重点讨论TeeInputStreamTeeOutputSteam。”Tee“(源自字母”T“)这个词通常用来描述一个输入要分成两个不同的输出。

Let’s look at an example that demonstrates how we can write a single input stream to two different output streams:

让我们看一个例子,演示我们如何将一个输入流写入两个不同的输出流中

String str = "Hello World.";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();

FilterOutputStream teeOutputStream
  = new TeeOutputStream(outputStream1, outputStream2);
new TeeInputStream(inputStream, teeOutputStream, true)
  .read(new byte[str.length()]);

assertEquals(str, String.valueOf(outputStream1));
assertEquals(str, String.valueOf(outputStream2));

5. Filters

5.过滤器

Commons IO includes a list of useful file filters. These can come in handy when a developer wants to narrow down to a specific desired list of files from a heterogeneous list of files.

Commons IO包括一个有用的文件过滤器列表。当开发者想从杂乱无章的文件列表中缩小到一个特定的所需文件列表时,这些过滤器就会派上用场。

The library also supports AND and OR logic operations on a given file list. Therefore, we can mix and match these filters to get the desired outcome.

该库还支持对给定文件列表的ANDOR逻辑操作。因此,我们可以混合和匹配这些过滤器来获得所需的结果。

Let’s see an example that makes use of WildcardFileFilter and SuffixFileFilter to retrieve files which have “ple” in their names with a “txt” suffix. Note that we wrap above filters using ANDFileFilter:

让我们看一个例子,利用WildcardFileFilterSuffixFileFilter来检索名称中含有”ple“且后缀为”txt“的文件。请注意,我们使用ANDFileFilter包装上述过滤器。

@Test
public void whenGetFilewith_ANDFileFilter_thenFind_sample_txt()
  throws IOException {

    String path = getClass().getClassLoader()
      .getResource("fileTest.txt")
      .getPath();
    File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));

    assertEquals("sample.txt",
      dir.list(new AndFileFilter(
        new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
        new SuffixFileFilter("txt")))[0]);
}

6. Comparators

6.比较者

The Comparator package provides different types of comparisons on files. We’ll explore two different comparators here.

Comparator包提供不同类型的文件比较。我们将在这里探讨两种不同的比较器。

6.1. PathFileComparator

6.1.PathFileComparator

The PathFileComparator class can be used to sort lists or arrays of files by their path either in a case-sensitive, case-insensitive, or system-dependent case-sensitive way. Let’s see how to sort file paths in the resources directory using this utility:

PathFileComparator类可用于按文件路径对列表或数组进行排序,可采用区分大小写、不区分大小写或与系统相关的区分大小写的方式。让我们看看如何使用这个工具对资源目录中的文件路径进行排序。

@Test
public void whenSortDirWithPathFileComparator_thenFirstFile_aaatxt() 
  throws IOException {
    
    PathFileComparator pathFileComparator = new PathFileComparator(
      IOCase.INSENSITIVE);
    String path = FilenameUtils.getFullPath(getClass()
      .getClassLoader()
      .getResource("fileTest.txt")
      .getPath());
    File dir = new File(path);
    File[] files = dir.listFiles();

    pathFileComparator.sort(files);

    assertEquals("aaa.txt", files[0].getName());
}

Note that we have used the IOCase.INSENSITIVE configuration. PathFileComparator also provides a number of singleton instances that have different case-sensitivity and reverse-sorting options.

请注意,我们使用了IOCase.INSENSITIVE配置。PathFileComparator还提供了一些单体实例,它们具有不同的大小写敏感度和反向排序选项

These static fields include PATH_COMPARATOR, PATH_INSENSITIVE_COMPARATOR, PATH_INSENSITIVE_REVERSE, PATH_SYSTEM_COMPARATOR, to name few.

这些静态字段包括PATH_COMPARATOR、PATH_INSENSITIVE_COMPARATOR、PATH_INSENSITIVE_REVERSE、PATH_SYSTEM_COMPARATOR,等等。

6.2. SizeFileComparator

6.2.SizeFileComparator

SizeFileComparator is, as its name suggests, used to compare the sizes (lengths) of two files. It returns a negative integer value if the first file’s size is less than that of the second file. It returns zero if the file sizes are equal and a positive value if the first file’s size is greater than the second file’s size.

SizeFileComparator,如其名称所示,用于比较两个文件的大小(长度)。如果第一个文件的大小小于第二个文件的大小,它返回一个负的整数值。如果文件大小相等,则返回0;如果第一个文件的大小大于第二个文件的大小,则返回一个正值。

Let’s write a unit test demonstrating a comparison of file sizes:

让我们写一个单元测试,演示一下文件大小的比较。

@Test
public void whenSizeFileComparator_thenLargerFile_large()
  throws IOException {

    SizeFileComparator sizeFileComparator = new SizeFileComparator();
    File largerFile = FileUtils.getFile(getClass().getClassLoader()
      .getResource("fileTest.txt")
      .getPath());
    File smallerFile = FileUtils.getFile(getClass().getClassLoader()
      .getResource("sample.txt")
      .getPath());

    int i = sizeFileComparator.compare(largerFile, smallerFile);

    Assert.assertTrue(i > 0);
}

7. File Monitor

7.文件监控

The Commons IO monitor package provides the capability to track changes to a file or directory. Let’s see a quick example of how FileAlterationMonitor can be used together with FileAlterationObserver and FileAlterationListener to monitor a file or folder.

Commons的IO监控包提供了跟踪文件或目录变化的能力。让我们看一个快速的例子,说明FileAlterationMonitor如何与FileAlterationObserverFileAlterationListener一起用来监控一个文件或文件夹。

When FileAlterationMonitor starts, we’ll start receiving notifications for file changes on the directory that is being monitored:

FileAlterationMonitor启动时,我们将开始接收被监控的目录上的文件变化通知

FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);

FileAlterationListener fal = new FileAlterationListenerAdaptor() {

    @Override
    public void onFileCreate(File file) {
        // on create action
    }

    @Override
    public void onFileDelete(File file) {
        // on delete action
    }
};

observer.addListener(fal);
monitor.addObserver(observer);
monitor.start();

8. Conclusion

8.结论

This article covered some of the commonly used components of Commons IO package. However, the package does come with many other capabilities as well. Please refer to API documentation for more details.

这篇文章涵盖了Commons IO包的一些常用组件。然而,该包确实也有许多其他功能。请参考API文档以了解更多详情。

The code used in this example can be found in the GitHub project.

本例中使用的代码可以在GitHub项目中找到。