Apache Commons IO 快速指南



Apache Commons IO - 概述

Apache Commons IO 库提供各种实用程序类,用于常见的 文件IO 操作,涵盖广泛的用例。它有助于避免编写样板代码。Apache Commons IO 库提供以下类别的类:

  • 实用程序类 − 这些位于 org.apache.commons.io 包下的类提供文件和字符串比较。以下是一些示例。

    • IOUtils − 提供用于读取、写入和复制文件的实用程序方法。这些方法适用于 InputStream、OutputStream、Reader 和 Writer。

    • FilenameUtils − 提供无需使用 File 对象即可处理文件名的的方法。它在不同的操作系统上以类似的方式工作。

    • FileUtils − 提供用于操作文件的方法,例如移动、打开、检查是否存在、读取文件等。这些方法使用 File 对象。

    • IOCase − 提供用于字符串操作和比较的方法。

    • FileSystemUtils − 提供用于获取磁盘驱动器上可用空间的方法。

    • LineIterator − 提供一种灵活的方式来处理基于行的文件。

  • 过滤器类org.apache.commons.io.filefilter 包下的过滤器类提供根据逻辑条件而不是基于字符串的繁琐比较来过滤文件的方法。以下是一些示例。

    • NameFileFilter − 根据文件名进行过滤。

    • WildcardFileFilter − 使用提供的通配符过滤文件。

    • SuffixFileFilter − 基于后缀过滤文件。这用于检索特定类型的全部文件。

    • PrefixFileFilter − 基于前缀过滤文件。

    • OrFileFilter − 在文件过滤器列表中提供条件 OR 逻辑。如果列表中的任何过滤器返回 true,则返回 true。否则,返回 false。

    • AndFileFilter − 在文件过滤器列表中提供条件 AND 逻辑。如果列表中的任何过滤器返回 false,则返回 false。否则,返回 true。

  • 文件监控类org.apache.commons.io.monitor 包下的文件监控类提供对跟踪特定文件或文件夹中的更改的控制,并允许根据更改执行相应的操作。以下是一些示例。

    • FileEntry − 提供文件或目录的状态,某个时间点的文件属性。

    • FileAlterationObserver − 表示根目录下文件的狀態,检查文件系统并通知侦听器创建、更改或删除事件。

    • FileAlterationMonitor − 表示一个线程,该线程会生成一个监控线程,并在指定的时间间隔内触发任何已注册的 FileAlterationObserver。

  • 比较器类org.apache.commons.io.comparator 包下的文件监控类允许轻松比较和排序文件和目录。

    • NameFileComparator − 比较两个文件的名称。

    • SizeFileComparator − 比较两个文件的大小。

    • LastModifiedFileComparator − 比较两个文件的上次修改日期。

  • 流类org.apache.commons.io.input 包下有多个 InputStream 实现,org.apache.commons.io.output 包下有多个 OutputStream 实现,用于对流执行有用的任务。以下是一些示例。

    • NullOutputStream − 吸收所有发送的数据,不会产生任何错误。

    • TeeOutputStream − 将输出发送到两个流。

    • ByteArrayOutputStream − JDK 类的更快版本。

    • CountingOutputStream − 统计通过流的字节数。

    • CountingOutputStream − 统计通过流的字节数。

    • ProxyOutputStream − 将调用更改为代理流。

    • LockableFileWriter − 一个 FileWriter,用于创建锁文件并允许简单的跨线程文件锁处理。

Apache Commons IO - 环境设置

在本章中,我们将学习 Apache Commons IO 的本地环境设置,以及如何在 Windows 2000/XP、Windows 95/98/ME 等系统上设置 Commons IO 的路径。我们还将了解一些流行的 Java 编辑器以及如何下载 Commons IO 存档。

本地环境设置

系统要求

JDK Java SE 2 JDK 1.8 或更高版本
内存 1 GB RAM(推荐)
磁盘空间 无最低要求
操作系统版本 Windows XP 或更高版本,Linux

验证您的 Java 安装

首先,您需要在系统上安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据您正在使用的平台执行以下两个命令中的任何一个。

如果 Java 安装已正确完成,则它将显示当前版本和 Java 安装的规范。示例输出在下面的表格中给出。

平台 命令 示例输出
Windows

打开命令控制台并输入:

>java -version

java version "11.0.11" 2021-04-20 LTS

Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

打开命令终端并输入:

$java -version

java version "11.0.11" 2021-04-20 LTS

Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194)

Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

设置您的 Java 环境

设置环境变量 JAVA_HOME 以指向 Java 安装在您计算机上的基目录位置。例如:

序号 平台和描述
1

Windows

将 JAVA_HOME 设置为 C:\ProgramFiles\java\jdk11.0.11

2

Linux

export JAVA_HOME=/usr/local/java-current

将 Java 编译器位置的完整路径添加到系统路径。

序号 平台和描述
1

Windows

将字符串“C:\Program Files\Java\jdk11.0.11\bin”附加到系统变量 PATH 的末尾。

2

Linux

export PATH=$PATH:$JAVA_HOME/bin/

如上所述,从命令提示符执行命令 java -version

流行的 Java 编辑器

要编写 Java 程序,您需要一个文本编辑器。市场上有许多复杂的集成开发环境 (IDE)。但目前,您可以考虑以下其中一种:

  • 记事本 − 在 Windows 机器上,您可以使用任何简单的文本编辑器,例如记事本(推荐用于本教程)、TextPad。

  • Netbeans − 这是一款开源且免费的 Java IDE,可以从 www.netbeans.org/index.html 下载。

  • Eclipse − 这也是一个由 Eclipse 开源社区开发的 Java IDE,可以从 www.eclipse.org 下载。

下载 Common IO 存档

commons-io-2.11.0-bin.zip 下载 Apache Common IO jar 文件的最新版本。在撰写本教程时,我们下载了 commons-io-2.11.0-bin.zip 并将其复制到 C:\>Apache 文件夹。

操作系统 存档名称
Windows commons-io-2.11.0-bin.zip
Linux commons-io-2.11.0-bin.tar.gz
Mac commons-io-2.11.0-bin.tar.gz

设置 Apache Common IO 环境

设置APACHE_HOME环境变量以指向 Apache jar 文件存储在您计算机上的基目录位置。假设我们已在各个操作系统上的 Apache 文件夹中解压缩了commons-io-2.11.0-bin.zip,如下所示。

操作系统 输出
Windows 将环境变量 APACHE_HOME 设置为 C:\Apache
Linux export APACHE_HOME=/usr/local/Apache
Mac export APACHE_HOME=/Library/Apache

设置 CLASSPATH 变量

设置CLASSPATH环境变量以指向 Common IO jar 文件位置。假设您已在各个操作系统上的 Apache 文件夹中存储了commons-io-2.11.0-bin.zip,如下所示。

操作系统 输出
Windows 将环境变量 CLASSPATH 设置为 %CLASSPATH%;%APACHE_HOME%\commons-io-2.11.0.jar;。
Linux export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.11.0.jar:.
Mac export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.11.0.jar:.

Apache Commons IO - IOUtils 类

提供用于读取、写入和复制文件的实用程序方法。这些方法适用于 InputStream、OutputStream、Reader 和 Writer。

类声明

以下是org.apache.commons.io.IOUtils类的声明:

public class IOUtils
   extends Object

特性

  • 提供用于输入/输出操作的静态实用程序方法。

  • toXXX() - 从流读取数据。

  • write() - 将数据写入流。

  • copy() - 将所有数据从一个流复制到另一个流。

  • contentEquals - 比较两个流的内容。

IOUtils 类的示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;

public class IOTester {
   public static void main(String[] args) {
      try{
         //Using BufferedReader
         readUsingTraditionalWay();

         //Using IOUtils
         readUsingIOUtils();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   //reading a file using buffered reader line by line
   public static void readUsingTraditionalWay() throws IOException{
      try (BufferedReader bufferReader 
         = new BufferedReader( 
            new InputStreamReader(  
               new FileInputStream("input.txt") ) )) {
         String line;
         while ( ( line = bufferReader.readLine() ) != null ) {
            System.out.println( line );
         }
      }
   }

   //reading a file using IOUtils in one go
   public static void readUsingIOUtils() throws IOException {
      try(InputStream in = new FileInputStream("input.txt")){
         System.out.println( IOUtils.toString( in , "UTF-8") );
      }
   }
}

输出

它将打印以下结果。

Welcome to TutorialsPoint. Simply Easy Learning.
Welcome to TutorialsPoint. Simply Easy Learning.

Apache Commons IO - FileUtils 类

提供用于操作文件的方法,例如移动、打开、检查是否存在、读取文件等。这些方法使用 File 对象。

类声明

以下是org.apache.commons.io.FileUtils类的声明:

public class FileUtils
   extends Object

特性

  • 写入文件的方法。

  • 从文件读取的方法。

  • 创建目录(包括父目录)的方法。

  • 复制文件和目录的方法。

  • 删除文件和目录的方法。

  • 转换为和从 URL 转换的方法。

  • 按过滤器和扩展名列出文件和目录的方法。

  • 比较文件内容的方法。

  • 获取文件上次更改日期的方法。

  • 计算校验和的方法。

FileUtils 类的示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;

public class IOTester {
   public static void main(String[] args) {
      try{
         //Using FileUtils
         usingFileUtils();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingFileUtils() throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");

      //get the temp directory
      File tmpDir = FileUtils.getTempDirectory();

      System.out.println(tmpDir.getName());

      //copy file to temp directory
      FileUtils.copyFileToDirectory(file, tmpDir);

      //create a new file
      File newTempFile = FileUtils.getFile(tmpDir, file.getName());

      //get the content
      String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());

      //print the content
      System.out.println(data);
   }
}

输出

它将打印以下结果。

Temp
Welcome to TutorialsPoint. Simply Easy Learning.

Apache Commons IO - FilenameUtils 类

提供无需使用 File 对象即可处理文件名的的方法。它在不同的操作系统上以类似的方式工作。当从基于 Windows 的开发机器迁移到基于 Unix 的生产机器时,此类可以解决问题。

类声明

以下是org.apache.commons.io.FilenameUtils类的声明:

public class FilenameUtils
   extends Object

特性

此类在文件名中定义六个组件。考虑一个示例位置,例如C:\dev\project\file.txt。那么组件如下:

  • 前缀 - C:\

  • 相对路径 - dev\project\

  • 绝对路径 - C:\dev\project\

  • 名称 - file.txt

  • 基本名称 - file

  • 扩展名 - txt

要标识目录,请向文件名添加分隔符。

FilenameUtils 类的示例

IOTester.java

import java.io.IOException;
import org.apache.commons.io.FilenameUtils;

public class IOTester {
   public static void main(String[] args) {
      try{
         //Using FilenameUtils
         usingFilenameUtils();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingFilenameUtils() throws IOException {
      String path = "C:\\dev\\project\\file.txt";
      System.out.println("Full Path: " +FilenameUtils.getFullPath(path));
      System.out.println("Relative Path: " +FilenameUtils.getPath(path));
      System.out.println("Prefix: " +FilenameUtils.getPrefix(path));
      System.out.println("Extension: " + FilenameUtils.getExtension(path));
      System.out.println("Base: " + FilenameUtils.getBaseName(path));
      System.out.println("Name: " + FilenameUtils.getName(path));

      String filename = "C:/commons/io/../lang/project.xml";
      System.out.println("Normalized Path: " + FilenameUtils.normalize(filename));
   }
}

输出

它将打印以下结果。

Full Path: C:\dev\project\
Relative Path: dev\project\
Prefix: C:\
Extension: txt
Base: file
Name: file.txt
Normalized Path: C:\commons\lang\project.xml

Apache Commons IO - FileSystemUtils 类

提供用于获取磁盘驱动器上可用空间的方法。

类声明

以下是org.apache.commons.io.FileSystemUtils类的声明:

public class FileSystemUtils
   extends Object

FileSystemUtils类示例

IOTester.java

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;

public class IOTester {
   public static void main(String[] args) {
      try{
         System.out.println("Free Space " + FileSystemUtils.freeSpaceKb("C:/") + " Bytes");
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }
}

输出

它将打印以下结果。

Free Space 61355640 kb

Apache Commons IO - IOCase 枚举

IO大小写敏感性的枚举。不同的操作系统对文件名的大小写敏感性有不同的规则。例如,Windows对文件名不区分大小写,而Unix区分大小写。IOCase捕获了这种差异,提供了一个枚举来控制如何执行文件名比较。它还提供使用枚举执行比较的方法。

枚举声明

以下是org.apache.commons.io.IOCase枚举的声明:

public enum IOCase
   extends Enum<IOCase>
      implements Serializable

IOCase枚举示例

IOTester.java

import java.io.IOException;
import org.apache.commons.io.IOCase;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingIOCase();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingIOCase() throws IOException {
      String text = "Welcome to TutorialsPoint. Simply Easy Learning.";
      String text1 = "WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.";

      System.out.println("Ends with Learning (case sensitive): " +
      IOCase.SENSITIVE.checkEndsWith(text1, "Learning."));

      System.out.println("Ends with Learning (case insensitive): " +
      IOCase.INSENSITIVE.checkEndsWith(text1, "Learning."));

      System.out.println("Equality Check  (case sensitive): " +
      IOCase.SENSITIVE.checkEquals(text, text1));

      System.out.println("Equality Check  (case insensitive): " +
      IOCase.INSENSITIVE.checkEquals(text, text1));
   }
}

输出

它将打印以下结果。

Ends with Learning (case sensitive): false
Ends with Learning (case insensitive): true
Equality Check  (case sensitive): false
Equality Check  (case insensitive): true

Apache Commons IO - LineIterator 类

提供了一种灵活的方式来处理基于行的文件。

类声明

以下是org.apache.commons.io.LineIterator类的声明:

public class LineIterator
   extends Object
      implements Iterator<String>, Closeable

LineIterator类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.

IOTester.java

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingLineIterator();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingLineIterator() throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");

      try(LineIterator lineIterator = FileUtils.lineIterator(file)){
         System.out.println("Contents of input.txt");
         while (lineIterator.hasNext()) {
            System.out.println(lineIterator.next());
         }
      }
   }
}

输出

它将打印以下结果。

Contents of input.txt
Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.

Apache Commons IO - NameFileFilter 类

根据名称过滤文件名。

类声明

以下是org.apache.commons.io.filefilter.NameFileFilter类的声明:

public class NameFileFilter
   extends AbstractFileFilter
      implements Serializable

NameFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名为Input.txt的文件。

IOTester.java

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingNameFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingNameFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile with name input.txt\n");
      String[] acceptedNames = {"input", "input.txt"};
      String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.INSENSITIVE) );

      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with name input.txt

input.txt

Apache Commons IO - WildcardFileFilter 类

使用提供的通配符过滤文件。

类声明

以下是org.apache.commons.io.filefilter.WildcardFileFilter类的声明:

public class WildcardFileFilter
   extends AbstractFileFilter
      implements Serializable

WildcardFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名称以t结尾的文件。

IOTester.java

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

import org.apache.commons.io.filefilter.WildcardFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingWildcardFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }
   public static void usingWildcardFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile name ending with t.\n");
      String[] filesNames = currentDirectory.list( new WildcardFileFilter("*t") );
      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File name ending with t

.project
input.txt

Apache Commons IO - SuffixFileFilter 类

基于后缀过滤文件。这用于检索特定类型的文件。

类声明

以下是org.apache.commons.io.filefilter.SuffixFileFilter类的声明:

public class SuffixFileFilter
   extends AbstractFileFilter
      implements Serializable

SuffixFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤扩展名为txt的文件。

IOTester.java

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

import org.apache.commons.io.filefilter.SuffixFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingSuffixFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingSuffixFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile with extenstion txt\n");
      String[] filesNames = currentDirectory.list( new SuffixFileFilter("txt") );
      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with extenstion txt

input.txt

Apache Commons IO - PrefixFileFilter 类

基于前缀过滤文件。

类声明

以下是org.apache.commons.io.filefilter.PrefixFileFilter类的声明:

public class PrefixFileFilter
   extends AbstractFileFilter
      implements Serializable

PrefixFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名称以input开头的文件。

IOTester.java

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

import org.apache.commons.io.filefilter.PrefixFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingPrefixFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingPrefixFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile starting with input\n");
      String[] filesNames = currentDirectory.list( new PrefixFileFilter("input") );
      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with extenstion txt

input.txt

Apache Commons IO - OrFileFilter 类

在文件过滤器列表中提供条件OR逻辑。如果列表中的任何过滤器返回true,则返回true。否则,返回false。

类声明

以下是org.apache.commons.io.filefilter.OrFileFilter类的声明:

public class OrFileFilter
   extends AbstractFileFilter
      implements ConditionalFileFilter, Serializable

OrFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名称以`.`开头或以t结尾的文件。

IOTester.java

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

import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingOrFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingOrFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile starting with . or ends with t\n");
      String[] filesNames = currentDirectory.list(
         new OrFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")));
      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File starting with . or ends with t

.classpath
.project
.settings
input.txt

Apache Commons IO - AndFileFilter 类

在文件过滤器列表中提供条件AND逻辑。如果列表中的所有过滤器都返回true,则返回true。否则,返回false。

类声明

以下是org.apache.commons.io.filefilter.AndFileFilter类的声明:

public class AndFileFilter
   extends AbstractFileFilter
      implements ConditionalFileFilter, Serializable

AndFileFilter类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录,然后过滤名称以`.`开头并以t结尾的文件。

IOTester.java

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

import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingAndFileFilter();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }
   public static void usingAndFileFilter() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for ( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
      System.out.println("\nFile starting with . and ends with t\n");
      String[] filesNames = currentDirectory.list(
         new AndFileFilter(new PrefixFileFilter("."), new WildcardFileFilter("*t")));
      for ( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

输出

它将打印以下结果。

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File starting with . or ends with t

.project

Apache Commons IO - FileEntry 类

提供文件或目录的状态,某个时间点的文件属性。

类声明

以下是org.apache.commons.io.monitor.FileEntry类的声明:

public class FileEntry
   extends Object
      implements Serializable

特性

FileEntry类对象提供以下某个时间点的文件属性:

  • getName() - 文件名。

  • exists() - 检查文件是否存在。

  • isDirectory() - 检查文件是否为目录。

  • lastModified() - 获取最后修改的日期时间。

  • listFiles() - 获取目录的内容。

FileEntry类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileEntry;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingFileEntry();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingFileEntry() throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");

      FileEntry fileEntry = new FileEntry(file);

      System.out.println("Monitored File: " + fileEntry.getFile());
      System.out.println("File name: " + fileEntry.getName());
      System.out.println("Is Directory: " + fileEntry.isDirectory());
   }
}

输出

它将打印以下结果。

Monitored File: input.txt
File name: input.txt
Is Directory: false

Apache Commons IO - FileAlterationObserver 类

表示根目录下文件的狀態,检查文件系统并通知监听器创建、更改或删除事件。

类声明

以下是org.apache.commons.io.monitor.FileAlterationObserver类的声明:

public class FileAlterationObserver
   extends Object
      implements Serializable

FileAlterationObserver类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

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

import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingFileAlterationObserver();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingFileAlterationObserver() throws IOException {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));   
      File parentDirectory = FileUtils.getFile(parent);

      FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);

      observer.addListener(new FileAlterationListenerAdaptor(){

         @Override
         public void onDirectoryCreate(File file) {
            System.out.println("Folder created: " + file.getName());
         }

         @Override
         public void onDirectoryDelete(File file) {
            System.out.println("Folder deleted: " + file.getName());
         } 

         @Override
         public void onFileCreate(File file) {
            System.out.println("File created: " + file.getName());
         }

         @Override
         public void onFileDelete(File file) {
            System.out.println("File deleted: " + file.getName());
         }  
      });

      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);

      try{
         monitor.start();

         //create a new directory
         File newFolder = new File("test");
         File newFile = new File("test1");

         newFolder.mkdirs();
         Thread.sleep(1000);
         newFile.createNewFile();
         Thread.sleep(1000);
         FileDeleteStrategy.NORMAL.delete(newFolder);
         Thread.sleep(1000);
         FileDeleteStrategy.NORMAL.delete(newFile);
         Thread.sleep(1000);

         monitor.stop(10000);

      }catch(IOException e){
         System.out.println(e.getMessage());
      } catch(InterruptedException e){
         System.out.println(e.getMessage());
      }catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

输出

它将打印以下结果。

Folder created: test
File created: test1
Folder deleted: test
File deleted: test1

Apache Commons IO - FileAlterationMonitor 类

表示一个线程,该线程会生成一个监控线程,并在指定的时间间隔内触发任何已注册的FileAlterationObserver。

类声明

以下是org.apache.commons.io.monitor.FileAlterationMonitor类的声明:

public final class FileAlterationMonitor
   extends Object
      implements Runnable

FileAlterationMonitor类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

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

import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingFileAlterationMonitor();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingFileAlterationMonitor() throws IOException {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));   
      File parentDirectory = FileUtils.getFile(parent);

      FileAlterationObserver observer = new FileAlterationObserver(parentDirectory);

      observer.addListener(new FileAlterationListenerAdaptor(){

         @Override
         public void onDirectoryCreate(File file) {
            System.out.println("Folder created: " + file.getName());
         }

         @Override
         public void onDirectoryDelete(File file) {
            System.out.println("Folder deleted: " + file.getName());
         } 

         @Override
         public void onFileCreate(File file) {
            System.out.println("File created: " + file.getName());
         }

         @Override
         public void onFileDelete(File file) {
            System.out.println("File deleted: " + file.getName());
         }  
      });

      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);

      try{
         monitor.start();

         //create a new directory
         File newFolder = new File("test");
         File newFile = new File("test1");

         newFolder.mkdirs();
         Thread.sleep(1000);
         newFile.createNewFile();
         Thread.sleep(1000);
         FileDeleteStrategy.NORMAL.delete(newFolder);
         Thread.sleep(1000);
         FileDeleteStrategy.NORMAL.delete(newFile);
         Thread.sleep(1000);

         monitor.stop(10000);

      }catch(IOException e){
         System.out.println(e.getMessage());
      } catch(InterruptedException e){
         System.out.println(e.getMessage());
      }catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

输出

它将打印以下结果。

Folder created: test
File created: test1
Folder deleted: test
File deleted: test1

Apache Commons IO - NameFileComparator 类

比较两个文件的名称。NameFileComparator可用于使用其名称(区分大小写、不区分大小写或系统相关的大小写敏感方式)对文件列表或数组进行排序。

类声明

以下是org.apache.commons.io.comparator.NameFileComparator类的声明:

public class NameFileComparator
   extends Object
      implements Serializable

NameFileComparator类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

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

import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingNameFileComparator();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingNameFileComparator() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      NameFileComparator comparator = new NameFileComparator(IOCase.INSENSITIVE);

      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));

      System.out.println("Sorted By Name: ");
      for(File file:sortedFiles){      
         System.out.println(file.getName());
      }
   }
}

输出

它将打印以下结果。

Sorted By Name: 
.classpath
.project
input.txt

Apache Commons IO - SizeFileComparator 类

比较两个文件/目录的大小。SizeFileComparator可用于根据其大小或子项数量对文件或目录列表或数组进行排序。

类声明

以下是org.apache.commons.io.comparator.SizeFileComparator类的声明:

public class SizeFileComparator
   extends Object
      implements Serializable

SizeFileComparator类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

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

import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingSizeFileComparator();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingSizeFileComparator() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      SizeFileComparator comparator = new SizeFileComparator();

      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));

      System.out.println("Sorted By Size: ");
      for(File file:sortedFiles){      
         System.out.println(file.getName() + ", size(kb) :" + file.length());
      }
   }
}

输出

它将打印以下结果。

Sorted By Size: 
input.txt, size:124
.project, size:382
.classpath, size:441

Apache Commons IO - LastModifiedFileComparator 类

比较两个文件/目录的最后修改日期。LastModifiedFileComparator可用于使用其最后修改日期对文件/目录列表或数组进行排序。

类声明

以下是org.apache.commons.io.comparator.LastModifiedFileComparator类的声明:

public class LastModifiedFileComparator
   extends Object
      implements Serializable

LastModifiedFileComparator类示例

这是我们需要解析的输入文件:

Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class IOTester {
   public static void main(String[] args) {
      try{
         usingLastModifiedFileComparator();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }

   public static void usingLastModifiedFileComparator() throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      LastModifiedFileComparator comparator = new LastModifiedFileComparator();

      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));

      System.out.println("Sorted By Last Modified date: ");
      for(File file:sortedFiles){      
         System.out.println(file.getName() + ", Modified on: " + new Date(file.lastModified()));
      }
   }
}

输出

它将打印以下结果。

Sorted By Last Modified date: 
.project, Modified on: Thu Oct 12 19:06:45 IST 2017
.classpath, Modified on: Mon Nov 20 13:09:55 IST 2017
input.txt, Modified on: Mon Nov 20 19:27:55 IST 2017

Apache Commons IO - TeeInputStream 类

这是一个InputStream代理,它会将从代理流读取的所有字节的副本透明地写入给定的OutputStream。调用此代理上的close()方法时,将关闭代理输入流。它可以用于同时操作两个流。

类声明

以下是org.apache.commons.io.input.TeeInputStream类的声明:

public class TeeInputStream
   extends ProxyInputStream

TeeInputStream类示例

在此示例中,关闭TeeInputStream会同时关闭TeeInputStream和TeeOutputStream对象。

IOTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;

public class IOTester {
   private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";

   public static void main(String[] args) {
      try{
         usingTeeInputStream();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }
   public static void usingTeeInputStream() throws IOException {
      TeeInputStream teeInputStream = null;
      TeeOutputStream teeOutputStream = null;
      try {
         ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
         ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
         ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();

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

         System.out.println("Output stream 1: " + outputStream1.toString());
         System.out.println("Output stream 2: " + outputStream2.toString());

      } catch (IOException e) {
         System.out.println(e.getMessage());
      } finally {
         //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.       
         try { 
            teeInputStream.close(); 
         }
         catch (IOException e) { 
            System.out.println(e.getMessage());
         }
      }
   }
}

输出

它将打印以下结果。

Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.

Apache Commons IO - TeeOutputStream 类

TeeOutputStream拆分OutputStream。它以unix的'tee'命令命名。它允许将流分支到两个流。

类声明

以下是org.apache.commons.io.output.TeeOutputStream类的声明:

public class TeeOutputStream
   extends ProxyOutputStream

TeeOutputStream类示例

在此示例中,TeeOutputStream接受两个输出流作为参数,并将数据传递到TeeOutputStream,并将数据设置为两个输出流。

IOTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;

public class IOTester {
   private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";
   public static void main(String[] args) {
      try{
         usingTeeInputStream();
      }catch(IOException e){
         System.out.println(e.getMessage());
      }
   }
   public static void usingTeeInputStream() throws IOException {
      TeeInputStream teeInputStream = null;
      TeeOutputStream teeOutputStream = null;
      try {
         ByteArrayInputStream inputStream = new ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
         ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
         ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();

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

         System.out.println("Output stream 1: " + outputStream1.toString());
         System.out.println("Output stream 2: " + outputStream2.toString());

      } catch (IOException e) {
         System.out.println(e.getMessage());
      } finally {
         //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.       
         try { 
            teeInputStream.close(); 
         }
         catch (IOException e) { 
            System.out.println(e.getMessage());
         }
      }
   }
}

输出

它将打印以下结果。

Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.
广告
© . All rights reserved.