- Apache Commons IO 教程
- Apache Commons IO - 主页
- Apache Commons IO - 概述
- Apache Commons IO - 环境设置
- Apache Commons IO - IOUtils
- Apache Commons IO - FileUtils
- Apache Commons IO - FilenameUtils
- Apache Commons IO - FileSystemUtils
- Apache Commons IO - IO案例
- Apache Commons IO - LineIterator
- Apache Commons IO - NameFileFilter
- Apache Commons IO - WildcardFileFilter
- Apache Commons IO - 后缀文件过滤器
- Apache Commons IO - PrefixFileFilter
- Apache Commons IO - OrFileFilter
- Apache Commons IO - AndFileFilter
- Apache Commons IO - FileEntry
- Apache Commons IO - FileAlterationObserver
- Apache Commons IO - FileAlterationMonitor
- Apache Commons IO - NameFileComparator
- Apache Commons IO - SizeFileComparator
- 最后修改文件比较器
- Apache Commons IO - TeeInputStream
- Apache Commons IO - TeeOutputStream
- Apache Commons IO - 有用资源
- Apache Commons IO - 快速指南
- Apache Commons IO - 有用资源
- Apache Commons IO - 讨论
Apache Commons IO - 快速指南
Apache Commons IO - 概述
Apache Commons IO 库为文件 IO 的常见操作提供了各种实用程序类,涵盖了广泛的用例。它有助于避免编写样板代码。Apache Commons IO 库提供以下类别的类:
实用程序类- org.apache.commons.io包下的这些类提供文件和字符串比较。以下是一些示例。
IOUtils - 提供读取、写入和复制文件的实用方法。这些方法适用于 InputStream、OutputStream、Reader 和 Writer。
FilenameUtils - 提供在不使用文件对象的情况下处理文件名的方法。它以类似的方式在不同的操作系统上工作。
FileUtils - 提供操作文件的方法,如移动、打开、检查存在、读取文件等。这些方法使用文件对象。
IOCas - 提供字符串操作和比较的方法。
FileSystemUtils - 提供获取磁盘驱动器上可用空间的方法。
LineIterator - 提供一种灵活的方式来处理基于行的文件。
过滤器类- org.apache.commons.io.filefilter包下的过滤器类提供了基于逻辑标准而不是基于字符串的繁琐比较来过滤文件的方法。以下是一些示例。
NameFileFilter - 过滤文件名中的名称。
WildcardFileFilter - 使用提供的通配符过滤文件。
SuffixFileFilter - 根据后缀过滤文件。这用于检索特定类型的所有文件。
PrefixFileFilter - 根据前缀过滤文件。
OrFileFilter - 在文件过滤器列表中提供条件 OR 逻辑。如果列表中的任何过滤器返回 true,则返回 true。否则,返回 false。
AndFileFilter - 提供跨文件过滤器列表的条件与逻辑。如果列表中的任何过滤器返回 false,则返回 false。否则,返回 true。
文件监视器类- org.apache.commons.io.monitor包下的文件监视器类提供了跟踪特定文件或文件夹中的更改的控制,并允许对更改进行相应的操作。以下是一些示例。
FileEntry - 提供文件或目录的状态、某个时间点的文件属性。
FileAlterationObserver - 表示根目录下文件的状态,检查文件系统并通知侦听器创建、更改或删除事件。
FileAlterationMonitor - 表示一个线程,该线程生成一个监视线程,以指定的时间间隔触发任何已注册的 FileAlterationObserver。
比较器类- org.apache.commons.io.comparator包下的文件监视器类允许轻松比较和排序文件和目录。
NameFileComparator - 比较两个文件的名称。
SizeFileComparator - 比较两个文件的大小。
LastModifiedFileComparator - 比较两个文件的最后修改日期。
Stream 类- 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-版本 |
java 版本“11.0.11”2021-04-20 LTS Java(TM) SE 运行时环境 18.9(内部版本 11.0.11+9-LTS-194) Java HotSpot(TM) 64 位服务器 VM 18.9(内部版本 11.0.11+9-LTS-194,混合模式) |
| Linux |
打开命令终端并输入 - $java-版本 |
java 版本“11.0.11”2021-04-20 LTS 打开JDK运行时环境18.9(内部版本11.0.11+9-LTS-194) 打开JDK 64位服务器VM(内部版本11.0.11+9-LTS-194,混合模式) |
我们假设本教程的读者已在其系统上安装了 Java SDK 版本 11.0.11。
如果您没有 Java SDK,请从www.oracle.com/technetwork/java/javase/downloads/index.html下载其当前版本并进行安装。
设置您的 Java 环境
将环境变量 JAVA_HOME 设置为指向计算机上安装 Java 的基本目录位置。例如,
| 先生。 | 平台及描述 |
|---|---|
| 1 | Windows 将 JAVA_HOME 设置为 C:\ProgramFiles\java\jdk11.0.11 |
| 2 | Linux 导出 JAVA_HOME = /usr/local/java-current |
将 Java 编译器位置的完整路径附加到系统路径。
| 先生。 | 平台及描述 |
|---|---|
| 1 | Windows 将字符串“C:\Program Files\Java\jdk11.0.11\bin”附加到系统变量 PATH 的末尾。 |
| 2 | Linux 导出路径=$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下载。
下载通用 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 |
| 苹果 | commons-io-2.11.0-bin.tar.gz |
设置Apache通用IO环境
将APACHE_HOME环境变量设置为指向计算机上存储 Apache jar 的基本目录位置。假设我们已经在各种操作系统上的 Apache 文件夹中提取了commons-io-2.11.0-bin.zip ,如下所示。
| 操作系统 | 输出 |
|---|---|
| Windows | 将环境变量 APACHE_HOME 设置为 C:\Apache |
| Linux | 导出 APACHE_HOME=/usr/local/Apache |
| 苹果 | 导出 APACHE_HOME=/库/Apache |
设置 CLASSPATH 变量
将CLASSPATH环境变量设置为指向 Common IO jar 位置。假设您已将commons-io-2.11.0-bin.zip存储在各种操作系统上的 Apache 文件夹中,如下所示。
| 操作系统 | 输出 |
|---|---|
| Windows | 将环境变量 CLASSPATH 设置为 %CLASSPATH%;%APACHE_HOME%\commons-io-2.11.0.jar;。 |
| Linux | 导出 CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.11.0.jar:。 |
| 苹果 | 导出 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 类
提供操作文件的方法,如移动、打开、检查文件是否存在、读取文件等。这些方法使用文件对象。
类别声明
以下是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 类
提供在不使用文件对象的情况下处理文件名的方法。它以类似的方式在不同的操作系统上工作。此类解决从基于 Windows 的开发机器迁移到基于 Unix 的生产机器时出现的问题。
类别声明
以下是org.apache.commons.io.FilenameUtils类的声明-
public class FilenameUtils extends Object
特征
此类定义文件名中的六个组成部分。考虑一个示例位置C:\dev\project\file.txt。那么组件是
前缀 - C:\
相对路径 - dev\project\
绝对路径 - C:\dev\project\
名称 - 文件.txt
基本名称 - 文件
扩展名 - 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());
}
}
}
}
输出
它将打印以下结果。
input.txt的内容 欢迎来到教程点。简单易学。 学习网络技术, 准备考试, 在线代码, 全部集中在一处。
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 类
提供跨文件过滤器列表的条件和逻辑。如果列表中的所有过滤器都返回 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() - 文件名。
contains() - 检查文件是否存在。
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.