
- 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 - IOCase
- Apache Commons IO - LineIterator
- Apache Commons IO - NameFileFilter
- Apache Commons IO - WildcardFileFilter
- Apache Commons IO - SuffixFileFilter
- 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
- LastModifiedFileComparator
- 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 − 提供無需使用 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 |
開啟命令控制檯並輸入:
|
|
Linux |
開啟命令終端並輸入:
|
|
我們假設本教程的讀者在其系統上安裝了 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 編譯器位置的完整路徑新增到系統路徑。
序號 | 平臺和描述 |
---|---|
1 | Windows 將字串“C:\Program Files\Java\jdk11.0.11\bin”附加到系統變數 PATH 的末尾。 |
2 | Linux
|
如上所述,從命令提示符執行命令 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.