Commons Io 简明教程

Apache Commons IO - Quick Guide

Apache Commons IO - Overview

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

Apache Commons IO library provides various utility classes for common operations for File IO covering wide range of use cases. It helps avoid writing boilerplate code. Apache Commons IO library provides classes for following categories:

  1. Utility classes − These classes under org.apache.commons.io package provides file and string comparison. Following are some of the examples. IOUtils − Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer. FilenameUtils − Provides method to work with file names without using File Object. It works on different operating systems in similar way. FileUtils − Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object. IOCase − Provides method for string manipulation and comparison. FileSystemUtils − Provides method to get the free space on a disk drive. LineIterator − Provides a flexible way to work with a line-based file.

  2. Filter classes − Filter classes under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias instead of string based tedious comparisons. Following are some of the examples. NameFileFilter − Filters file-names for a name. WildcardFileFilter − Filters files using the supplied wildcards. SuffixFileFilter − Filters files based on suffix. This is used in retrieving all the files of a particular type. PrefixFileFilter − Filters files based on prefix. OrFileFilter − Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false. AndFileFilter − Provides conditional And logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.

  3. File Monitor classes − File monitor classes under org.apache.commons.io.monitor package provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples.

  4. Comparator classes − File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily. NameFileComparator − Compare the names of two files. SizeFileComparator − Compare the size of two files. LastModifiedFileComparator − Compare the last modified dates of two files.

  5. Stream classes − There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package to do useful tasks on streams. Following are some of the examples. NullOutputStream − absorbs all data sent with any error. TeeOutputStream − sends output to two streams. ByteArrayOutputStream − faster version of JDK class. CountingOutputStream − Counts the number of bytes passed through the stream. CountingOutputStream − Counts the number of bytes passed through the stream. ProxyOutputStream − Changes the calls to proxied stream. LockableFileWriter − A FileWriter to create lock files and allow simple cross thread file lock handling.

Apache Commons IO - Environment Setup

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

In this chapter, we will learn about the local environment setup of Apache Commons IO and how to set up the path of Commons IO for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons IO archive.

Local Environment Setup

System Requirements

JDK

Java SE 2 JDK 1.8 or above

Memory

1 GB RAM (recommended)

Disk Space

No minimum requirement

Operating System Version

Windows XP or above, Linux

Verify your Java Installation

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

First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.

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

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

Platform

Command

Sample Output

Windows

Open command console and type − >java -version

java version "11.0.11" 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

Open command terminal and type − $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)

  1. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.

  2. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

Set your Java Environment

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

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,

Sr.No.

Platform & Description

1

Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11

2

Linux Export JAVA_HOME = /usr/local/java-current

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

Append the full path of Java compiler location to the System Path.

Sr.No.

Platform & Description

1

Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH.

2

Linux Export PATH = $PATH:$JAVA_HOME/bin/

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

Execute the command java -version from the command prompt as explained above.

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

To write your Java programs, you need a text editor. There are many sophisticated integrated development environment (IDEs) available in the market. But for now, you can consider one of the following −

  1. Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  2. Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.

  3. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Download Common IO Archive

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

Download the latest version of Apache Common IO jar file from commons-io-2.11.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-io-2.11.0-bin.zip and copied it into C:\>Apache folder.

OS

Archive name

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

Set Apache Common IO Environment

设置 APACHE_HOME 环境变量以指向机器上存储 Apache jar 的基本目录位置。假设我们在各种操作系统中将 commons-io-2.11.0-bin.zip 提取到 Apache 文件夹中,如下所示。

Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we’ve extracted commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows.

OS

Output

Windows

Set the environment variable APACHE_HOME to C:\Apache

Linux

export APACHE_HOME=/usr/local/Apache

Mac

export APACHE_HOME=/Library/Apache

Set CLASSPATH Variable

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

Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-io-2.11.0-bin.zip in Apache folder on various Operating Systems as follows.

OS

Output

Windows

Set the environment variable CLASSPATH to %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 Class

提供用于读取、写入和复制文件的实用方法。这些方法与 InputStream、OutputStream、Reader 和 Writer 协同工作。

Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.

Class Declaration

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

Following is the declaration for org.apache.commons.io.IOUtils Class -

public class IOUtils
   extends Object

Features

  1. Provides static utility methods for input/output operations.

  2. toXXX() - reads data from a stream.

  3. write() - write data to a stream.

  4. copy() - copy all data to a stream to another stream.

  5. contentEquals - compare the contents of two streams.

Example of IOUtils Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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") );
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - FileUtils Class

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

Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.

Class Declaration

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

Following is the declaration for org.apache.commons.io.FileUtils Class -

public class FileUtils
   extends Object

Features

  1. Methods to write to a file.

  2. Methods to read from a file.

  3. Methods to make a directory including parent directories.

  4. Methods to copy files and directories.

  5. Methods to delete files and directories.

  6. Methods to convert to and from a URL.

  7. Methods to list files and directories by filter and extension.

  8. Methods to compare file content.

  9. Methods to file last changed date.

  10. Methods to calculating a checksum.

Example of FileUtils Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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);
   }
}

Output

它将打印以下结果。

It will print the following result.

Temp
Welcome to TutorialsPoint. Simply Easy Learning.

Apache Commons IO - FilenameUtils Class

提供一种方法来使用文件名而不使用 File Object 来工作。它以类似的方式在不同的操作系统上工作。此类解决从基于 Windows 的开发机器移至基于 Unix 的生产机器时的问题。

Provides method to work with file names without using File Object. It works on different operating systems in similar way. This class solves problems when moving from a Windows based development machine to a Unix based production machine.

Class Declaration

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

Following is the declaration for org.apache.commons.io.FilenameUtils Class -

public class FilenameUtils
   extends Object

Features

此类在文件名中定义了六个组件。考虑一个示例位置 C:\dev\project\file.txt 。然后组件是:

This class defines six components within a filename. Consider an example location as C:\dev\project\file.txt. Then the components are

  1. Prefix - C:\

  2. Relative Path - dev\project\

  3. Absolute path - C:\dev\project\

  4. Name - file.txt

  5. Base name - file

  6. Extension - txt

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

To identify a directory, add a separator to file name.

Example of FilenameUtils Class

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));
   }
}

Output

它将打印以下结果。

It will print the following result.

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 Class

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

Provides method to get the free space on a disk drive.

Class Declaration

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

Following is the declaration for org.apache.commons.io.FileSystemUtils Class -

public class FileSystemUtils
   extends Object

Example of FileSystemUtils Class

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());
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

Free Space 61355640 kb

Apache Commons IO - IOCase Enum

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

Enumeration of IO case sensitivity. Different Operating systems have different rules for case-sensitivity for file names. For example Windows is case-insensitive for file naming while Unix is case-sensitive. IOCase captures that difference, provides an enumeration to control how filename comparisons should be performed. It also provides methods to use the enumeration to perform comparisons.

Enum Declaration

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

Following is the declaration for org.apache.commons.io.IOCase Enum -

public enum IOCase
   extends Enum<IOCase>
      implements Serializable

Example of IOCase Enum

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));
   }
}

Output

它将打印以下结果。

It will print the following result.

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 Class

提供了一种使用基于行的文件的方法。

Provides a flexible way to work with a line-based file.

Class Declaration

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

Following is the declaration for org.apache.commons.io.LineIterator Class -

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

Example of LineIterator Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
         }
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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 Class

按名称筛选文件名。

Filters file-names for a name.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.NameFileFilter Class -

public class NameFileFilter
   extends AbstractFileFilter
      implements Serializable

Example of NameFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

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

Let’s print all files and directories in the current directory and then filter a file whose name is 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with name input.txt

input.txt

Apache Commons IO - WildcardFileFilter Class

使用提供的通配符筛选文件。

Filters files using the supplied wildcards.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.WildcardFileFilter Class -

public class WildcardFileFilter
   extends AbstractFileFilter
      implements Serializable

Example of WildcardFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

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

Let’s print all files and directories in the current directory and then filter a file whose name ends with 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File name ending with t

.project
input.txt

Apache Commons IO - SuffixFileFilter Class

根据后缀筛选文件。这用于检索特定类型的所有文件。

Filters files based on suffix. This is used in retrieving all the files of a particular type.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.SuffixFileFilter Class -

public class SuffixFileFilter
   extends AbstractFileFilter
      implements Serializable

Example of SuffixFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

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

Let’s print all files and directories in the current directory and then filter a file with extension 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with extenstion txt

input.txt

Apache Commons IO - PrefixFileFilter Class

根据前缀筛选文件。

Filters files based on prefix.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.PrefixFileFilter Class -

public class PrefixFileFilter
   extends AbstractFileFilter
      implements Serializable

Example of PrefixFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

让我们打印当前目录中的所有文件和目录, 然后使用以输入开头的名称过滤一个文件。

Let’s print all files and directories in the current directory and then filter a file with name starting with 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File with extenstion txt

input.txt

Apache Commons IO - OrFileFilter Class

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

Provides conditional OR logic across a list of file filters. Returns true if any filters in the list return true. Otherwise, it returns false.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.OrFileFilter Class -

public class OrFileFilter
   extends AbstractFileFilter
      implements ConditionalFileFilter, Serializable

Example of OrFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

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

Let’s print all files and directories in the current directory and then filter a file with name starting with . or ends with 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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 Class

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

Provides conditional And logic across a list of file filters. Returns true if all filters in the list return true. Otherwise, it returns false.

Class Declaration

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

Following is the declaration for org.apache.commons.io.filefilter.AndFileFilter Class -

public class AndFileFilter
   extends AbstractFileFilter
      implements ConditionalFileFilter, Serializable

Example of AndFileFilter Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

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

Let’s print all files and directories in the current directory and then filter a file with name starting with . and ends with 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]);
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

All files and Folders.

.classpath
.project
.settings
bin
input.txt
src

File starting with . or ends with t

.project

Apache Commons IO - FileEntry Class

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

Provides the state of a file or directory, File attributes at a point in time.

Class Declaration

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

Following is the declaration for org.apache.commons.io.monitor.FileEntry Class -

public class FileEntry
   extends Object
      implements Serializable

Features

FileEntry 类对象在时间点提供以下文件属性。

FileEntry class object provides following file attributes at a point in time.

  1. getName() - file name.

  2. exists() - checks if file exists or not.

  3. isDirectory() - checks if file is a directory.

  4. lastModified() - gives last modified date time.

  5. listFiles() - gives content of directory.

Example of FileEntry Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
   }
}

Output

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - FileAlterationObserver Class

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

Represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events.

Class Declaration

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

Following is the declaration for org.apache.commons.io.monitor.FileAlterationObserver Class -

public class FileAlterationObserver
   extends Object
      implements Serializable

Example of FileAlterationObserver Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - FileAlterationMonitor Class

Representa 一条线程, 它生成一个监视线程, 定期触发任何注册的 FileAlterationObserver。

Representa a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.

Class Declaration

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

Following is the declaration for org.apache.commons.io.monitor.FileAlterationMonitor Class -

public final class FileAlterationMonitor
   extends Object
      implements Runnable

Example of FileAlterationMonitor Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - NameFileComparator Class

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

Compare the names of two files. NameFileComparator can be used to sort lists or arrays of files using their name either in a case-sensitive, case-insensitive or system dependent case sensitive way.

Class Declaration

下面是 org.apache.commons.io.comparator.NameFileComparator 类的声明 -

Following is the declaration for org.apache.commons.io.comparator.NameFileComparator Class -

public class NameFileComparator
   extends Object
      implements Serializable

Example of NameFileComparator Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

Sorted By Name:
.classpath
.project
input.txt

Apache Commons IO - SizeFileComparator Class

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

Compare the sizes of two files/directory. SizeFileComparator can be used to sort lists or arrays of files using their size or directories based on their no. of children.

Class Declaration

下面是 org.apache.commons.io.comparator.SizeFileComparator 类的声明 -

Following is the declaration for org.apache.commons.io.comparator.SizeFileComparator Class -

public class SizeFileComparator
   extends Object
      implements Serializable

Example of SizeFileComparator Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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());
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - LastModifiedFileComparator Class

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

Compare the last modified dates of two files/directory. LastModifiedFileComparator can be used to sort lists or arrays of files/directories using their last modified dates.

Class Declaration

下面是 org.apache.commons.io.comparator.LastModifiedFileComparator 类的声明 -

Following is the declaration for org.apache.commons.io.comparator.LastModifiedFileComparator Class -

public class LastModifiedFileComparator
   extends Object
      implements Serializable

Example of LastModifiedFileComparator Class

以下是我们需要解析的输入文件 -

Here is the input file we need to parse −

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()));
      }
   }
}

Output

它将打印以下结果。

It will print the following result.

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 Class

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

It is an InputStream proxy that transparently writes a copy of all bytes read from the proxied stream to a given OutputStream. The proxied input stream is closed when the close() method on this proxy is called. It can be used to operate two streams collectively at a time.

Class Declaration

下面是 org.apache.commons.io.input.TeeInputStream 类的声明 -

Following is the declaration for org.apache.commons.io.input.TeeInputStream Class -

public class TeeInputStream
   extends ProxyInputStream

Example of TeeInputStream Class

在此示例中,关闭 TeeInputStream 会关闭 TeeInputStream 以及 TeeOutputStream 对象。

In this example, closing a TeeInputStream closes the TeeInputStream as well as TeeOutputStream objects.

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

它将打印以下结果。

It will print the following result.

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

Apache Commons IO - TeeOutputStream Class

TeeOutputStream 拆分 OutputStream。它以 Unix“tee”命令命名。它允许流分支到两个流。

TeeOutputStream splits OutputStream. It is named after the unix 'tee' command. It allows a stream to be branched to two streams.

Class Declaration

下面是 org.apache.commons.io.output.TeeOutputStream 类的声明 -

Following is the declaration for org.apache.commons.io.output.TeeOutputStream Class -

public class TeeOutputStream
   extends ProxyOutputStream

Example of TeeOutputStream Class

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

In this example, TeeOutputStream accepts two output streams as parameter and passing data to TeeOutputStream set data to both output streams.

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

它将打印以下结果。

It will print the following result.

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