日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Apache Commons IO教程:初学者指南

發布時間:2023/12/3 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Apache Commons IO教程:初学者指南 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Apache Commons IO是由Apache Foundation創建和維護的Java庫。 它提供了許多類,使開發人員可以輕松地完成常見任務,并且減少樣板代碼 ,而每個項目都需要一遍又一遍地編寫此類庫的重要性是巨大的,因為它們已經成熟由經驗豐富的開發人員進行維護 ,他們已經考慮了每種可能的情況,或者修復了各種錯誤。

在此示例中,我們將根據功能所屬的org.apache.commons.io包介紹一些具有不同功能的方法。 我們不會在庫中深入研究,因為它巨大,但是我們將提供一些常見用法的示例,這些示例對于每個開發人員(無論初學者或不入門)都可以派上用場。

1. Apache Commons IO示例

該示例的代碼將分為幾個類,并且每個類都代表Apache Commons IO涵蓋的特定領域。 這些區域是:

  • 實用程序類
  • 輸入項
  • 輸出量
  • 篩選器
  • 比較器
  • 文件監控

為了使事情更清楚,我們將輸出分成多個 ,每個創建的類一個。 我們還在項目文件夾(名為ExampleFolder )內創建了一個目錄,其中包含將在此示例中使用的各種文件,以顯示各種類的功能。

注意:為了使用org.apache.commons.io ,您需要下載jar文件(在此處找到),并通過右鍵單擊項目文件夾-> Build Path->將它們添加到Eclipse項目的構建路徑中。添加外部檔案。

ApacheCommonsExampleMain.java

public class ApacheCommonsExampleMain {public static void main(String[] args) {UtilityExample.runExample();FileMonitorExample.runExample();FiltersExample.runExample();InputExample.runExample();OutputExample.runExample();ComparatorExample.runExample();} }

這是將用于運行示例中其他類的方法的主要類。 您可以注釋某些類以查看所需的輸出。

1.1實用程序類

包org.apache.commons.io內有各種實用程序類,其中大多數與文件操作和字符串比較有關。 我們在這里使用了一些最重要的方法:

  • FilenameUtils :此類具有使用文件名的方法,主要要點是使每個OS的工作更輕松(在Unix和Windows系統中同樣有效)。
  • FileUtils :它提供用于文件操作 (移動,打開和讀取文件,檢查文件是否存在等)的方法。
  • IOCase :字符串操作和比較方法。
  • FileSystemUtils :其方法返回指定驅動器的可用空間。

UtilityExample.java

import java.io.File; import java.io.IOException;import org.apache.commons.io.FileSystemUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.io.IOCase;public final class UtilityExample {// We are using the file exampleTxt.txt in the folder ExampleFolder,// and we need to provide the full path to the Utility classes.private static final String EXAMPLE_TXT_PATH ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";private static final String PARENT_DIR ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample";public static void runExample() throws IOException {System.out.println("Utility Classes example...");// FilenameUtilsSystem.out.println("Full path of exampleTxt: " +FilenameUtils.getFullPath(EXAMPLE_TXT_PATH));System.out.println("Full name of exampleTxt: " +FilenameUtils.getName(EXAMPLE_TXT_PATH));System.out.println("Extension of exampleTxt: " +FilenameUtils.getExtension(EXAMPLE_TXT_PATH));System.out.println("Base name of exampleTxt: " +FilenameUtils.getBaseName(EXAMPLE_TXT_PATH));// FileUtils// We can create a new File object using FileUtils.getFile(String)// and then use this object to get information from the file.File exampleFile = FileUtils.getFile(EXAMPLE_TXT_PATH);LineIterator iter = FileUtils.lineIterator(exampleFile);System.out.println("Contents of exampleTxt...");while (iter.hasNext()) {System.out.println("\t" + iter.next());}iter.close();// We can check if a file exists somewhere inside a certain directory.File parent = FileUtils.getFile(PARENT_DIR);System.out.println("Parent directory contains exampleTxt file: " +FileUtils.directoryContains(parent, exampleFile));// IOCaseString str1 = "This is a new String.";String str2 = "This is another new String, yes!";System.out.println("Ends with string (case sensitive): " +IOCase.SENSITIVE.checkEndsWith(str1, "string."));System.out.println("Ends with string (case insensitive): " +IOCase.INSENSITIVE.checkEndsWith(str1, "string."));System.out.println("String equality: " +IOCase.SENSITIVE.checkEquals(str1, str2));// FileSystemUtilsSystem.out.println("Free disk space (in KB): " + FileSystemUtils.freeSpaceKb("C:"));System.out.println("Free disk space (in MB): " + FileSystemUtils.freeSpaceKb("C:") / 1024);} }

輸出量

Utility Classes example... Full path of exampleTxt: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\ Full name of exampleTxt: exampleTxt.txt Extension of exampleTxt: txt Base name of exampleTxt: exampleTxt Contents of exampleTxt...This is an example text file.We will use it for experimenting with Apache Commons IO. Parent directory contains exampleTxt file: true Ends with string (case sensitive): false Ends with string (case insensitive): true String equality: false Free disk space (in KB): 32149292 Free disk space (in MB): 31395

1.2文件監控器

org.apache.commons.io.monitor軟件包包含可以獲取有關文件的特定信息的方法,但更重要的是,它可以創建可用于跟蹤特定文件或文件夾中的更改并根據更改執行操作的處理程序。 。 讓我們看一下代碼:

FileMonitorExample.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; import org.apache.commons.io.monitor.FileEntry;public final class FileMonitorExample {private static final String EXAMPLE_PATH ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleFileEntry.txt";private static final String PARENT_DIR ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";private static final String NEW_DIR ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newDir";private static final String NEW_FILE ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newFile.txt";public static void runExample() {System.out.println("File Monitor example...");// FileEntry// We can monitor changes and get information about files// using the methods of this class.FileEntry entry = new FileEntry(FileUtils.getFile(EXAMPLE_PATH));System.out.println("File monitored: " + entry.getFile());System.out.println("File name: " + entry.getName());System.out.println("Is the file a directory?: " + entry.isDirectory());// File Monitoring// Create a new observer for the folder and add a listener// that will handle the events in a specific directory and take action.File parentDir = FileUtils.getFile(PARENT_DIR);FileAlterationObserver observer = new FileAlterationObserver(parentDir);observer.addListener(new FileAlterationListenerAdaptor() {@Overridepublic void onFileCreate(File file) {System.out.println("File created: " + file.getName());}@Overridepublic void onFileDelete(File file) {System.out.println("File deleted: " + file.getName());}@Overridepublic void onDirectoryCreate(File dir) {System.out.println("Directory created: " + dir.getName());}@Overridepublic void onDirectoryDelete(File dir) {System.out.println("Directory deleted: " + dir.getName());}});// Add a monior that will check for events every x ms,// and attach all the different observers that we want.FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);try {monitor.start();// After we attached the monitor, we can create some files and directories// and see what happens!File newDir = new File(NEW_DIR);File newFile = new File(NEW_FILE);newDir.mkdirs();newFile.createNewFile();Thread.sleep(1000);FileDeleteStrategy.NORMAL.delete(newDir);FileDeleteStrategy.NORMAL.delete(newFile);Thread.sleep(1000);monitor.stop();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}} }

輸出量

File Monitor example... File monitored: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt File name: exampleFileEntry.txt Is the file a directory?: false Directory created: newDir File created: newFile.txt Directory deleted: newDir File deleted: newFile.txt

讓我們看看這里發生了什么。 我們使用了org.apache.commons.io.monitor包中的某些類,這些類使我們能夠創建偵聽特定事件的處理程序 (在本例中,該處理程序與文件,文件夾,目錄等有關)。 為了實現這一點,需要采取某些步驟:

  • 創建一個File對象,該對象是我們要偵聽更改的目錄的引用。
  • 創建一個FileAlterationObserver對象,該對象將觀察這些更改。
  • 使用addListener()方法將FileAlterationListenerAdaptor添加到觀察器。 您可以使用多種方法來創建適配器,但是在我們的示例中,我們使用了一個嵌套類,該類僅實現某些方法(示例要求所需要的方法)。
  • 創建一個FileAlterationMonitor并添加您擁有的觀察者以及間隔(以毫秒為單位)。
  • 使用start()方法啟動監視器,并在必要時使用stop()方法將其stop() 。
  • 1.3過濾器

    過濾器可以多種組合方式使用 。 他們的工作是使我們能夠輕松區分文件,并獲得滿足特定條件的文件。 我們還可以結合使用過濾器來執行邏輯比較并更精確地獲取文件,而無需在以后使用繁瑣的字符串比較。

    FiltersExample.java

    import java.io.File;import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.NotFileFilter; import org.apache.commons.io.filefilter.OrFileFilter; import org.apache.commons.io.filefilter.PrefixFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter;public final class FiltersExample {private static final String PARENT_DIR ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";public static void runExample() {System.out.println("File Filter example...");// NameFileFilter// Right now, in the parent directory we have 3 files:// directory example// file exampleEntry.txt// file exampleTxt.txt// Get all the files in the specified directory// that are named "example".File dir = FileUtils.getFile(PARENT_DIR);String[] acceptedNames = {"example", "exampleTxt.txt"};for (String file: dir.list(new NameFileFilter(acceptedNames, IOCase.INSENSITIVE))) {System.out.println("File found, named: " + file);}//WildcardFileFilter// We can use wildcards in order to get less specific results// ? used for 1 missing char// * used for multiple missing charsfor (String file: dir.list(new WildcardFileFilter("*ample*"))) {System.out.println("Wildcard file found, named: " + file);}// PrefixFileFilter // We can also use the equivalent of startsWith// for filtering files.for (String file: dir.list(new PrefixFileFilter("example"))) {System.out.println("Prefix file found, named: " + file);}// SuffixFileFilter// We can also use the equivalent of endsWith// for filtering files.for (String file: dir.list(new SuffixFileFilter(".txt"))) {System.out.println("Suffix file found, named: " + file);}// OrFileFilter // We can use some filters of filters.// in this case, we use a filter to apply a logical // or between our filters.for (String file: dir.list(new OrFileFilter(new WildcardFileFilter("*ample*"), new SuffixFileFilter(".txt")))) {System.out.println("Or file found, named: " + file);}// And this can become very detailed.// Eg, get all the files that have "ample" in their name// but they are not text files (so they have no ".txt" extension.for (String file: dir.list(new AndFileFilter( // we will match 2 filters...new WildcardFileFilter("*ample*"), // ...the 1st is a wildcard...new NotFileFilter(new SuffixFileFilter(".txt"))))) { // ...and the 2nd is NOT .txt.System.out.println("And/Not file found, named: " + file);}} }

    輸出量

    File Filter example... File found, named: example File found, named: exampleTxt.txt Wildcard file found, named: example Wildcard file found, named: exampleFileEntry.txt Wildcard file found, named: exampleTxt.txt Prefix file found, named: example Prefix file found, named: exampleFileEntry.txt Prefix file found, named: exampleTxt.txt Suffix file found, named: exampleFileEntry.txt Suffix file found, named: exampleTxt.txt Or file found, named: example Or file found, named: exampleFileEntry.txt Or file found, named: exampleTxt.txt And/Not file found, named: example

    1.4比較器

    org.apache.commons.io.comparator軟件包包含一些類,這些類使我們可以輕松地對文件和目錄進行比較和排序。 我們只需要提供文件列表,并根據類,以各種方式對它們進行比較。

    ComparatorExample.java

    import java.io.File; import java.util.Date;import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOCase; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.comparator.NameFileComparator; import org.apache.commons.io.comparator.SizeFileComparator;public final class ComparatorExample {private static final String PARENT_DIR ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";private static final String FILE_1 ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\example";private static final String FILE_2 ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";public static void runExample() {System.out.println("Comparator example...");//NameFileComparator// Let's get a directory as a File object// and sort all its files.File parentDir = FileUtils.getFile(PARENT_DIR);NameFileComparator comparator = new NameFileComparator(IOCase.SENSITIVE);File[] sortedFiles = comparator.sort(parentDir.listFiles());System.out.println("Sorted by name files in parent directory: ");for (File file: sortedFiles) {System.out.println("\t"+ file.getAbsolutePath());}// SizeFileComparator// We can compare files based on their size.// The boolean in the constructor is about the directories.// true: directory's contents count to the size.// false: directory is considered zero size.SizeFileComparator sizeComparator = new SizeFileComparator(true);File[] sizeFiles = sizeComparator.sort(parentDir.listFiles());System.out.println("Sorted by size files in parent directory: ");for (File file: sizeFiles) {System.out.println("\t"+ file.getName() + " with size (kb): " + file.length());}// LastModifiedFileComparator// We can use this class to find which file was more recently modified.LastModifiedFileComparator lastModified = new LastModifiedFileComparator();File[] lastModifiedFiles = lastModified.sort(parentDir.listFiles());System.out.println("Sorted by last modified files in parent directory: ");for (File file: lastModifiedFiles) {Date modified = new Date(file.lastModified());System.out.println("\t"+ file.getName() + " last modified on: " + modified);}// Or, we can also compare 2 specific files and find which one was last modified.// returns > 0 if the first file was last modified.// returns 0)System.out.println("File " + file1.getName() + " was modified last because...");elseSystem.out.println("File " + file2.getName() + "was modified last because...");System.out.println("\t"+ file1.getName() + " last modified on: " +new Date(file1.lastModified()));System.out.println("\t"+ file2.getName() + " last modified on: " +new Date(file2.lastModified()));} }

    輸出量

    Comparator example... Sorted by name files in parent directory: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comparator1.txtC:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comperator2.txtC:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleC:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txtC:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleTxt.txt Sorted by size files in parent directory: example with size (kb): 0exampleTxt.txt with size (kb): 87exampleFileEntry.txt with size (kb): 503comperator2.txt with size (kb): 1458comparator1.txt with size (kb): 4436 Sorted by last modified files in parent directory: exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014example last modified on: Sun Oct 26 23:42:55 EET 2014comparator1.txt last modified on: Tue Oct 28 14:48:28 EET 2014comperator2.txt last modified on: Tue Oct 28 14:48:52 EET 2014exampleFileEntry.txt last modified on: Tue Oct 28 14:53:50 EET 2014 File example was modified last because...example last modified on: Sun Oct 26 23:42:55 EET 2014exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014

    讓我們看看這里使用了哪些類:

    • NameFileComparator :根據文件名比較文件。
    • SizeFileComparator :根據文件大小比較文件。
    • LastModifiedFileComparator :根據文件的最后修改日期比較文件。

    您還應該在這里注意,比較可以在整個目錄中進行(使用sort()方法sort()它們進行排序),也可以在兩個文件中分別進行compare()使用compare() )。

    1.5輸入

    org.apache.commons.io.input包中有InputStream各種實現。 我們將研究最有用的一個TeeInputStream ,它同時使用InputStream和OutputStream作為參數,并自動將從輸入中讀取的字節復制到輸出中。 此外,通過使用第三個布爾值參數,最后只關閉TeeInputStream ,兩個附加流也將關閉。

    InputExample.java

    import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException;import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.TeeInputStream; import org.apache.commons.io.input.XmlStreamReader;public final class InputExample {private static final String XML_PATH ="C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\InputOutputExampleFolder\\web.xml";private static final String INPUT = "This should go to the output.";public static void runExample() {System.out.println("Input example...");XmlStreamReader xmlReader = null;TeeInputStream tee = null;try {// XmlStreamReader// We can read an xml file and get its encoding.File xml = FileUtils.getFile(XML_PATH);xmlReader = new XmlStreamReader(xml);System.out.println("XML encoding: " + xmlReader.getEncoding());// TeeInputStream// This very useful class copies an input stream to an output stream// and closes both using only one close() method (by defining the 3rd// constructor parameter as true).ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));ByteArrayOutputStream out = new ByteArrayOutputStream();tee = new TeeInputStream(in, out, true);tee.read(new byte[INPUT.length()]);System.out.println("Output stream: " + out.toString()); } catch (IOException e) {e.printStackTrace();} finally {try { xmlReader.close(); }catch (IOException e) { e.printStackTrace(); }try { tee.close(); }catch (IOException e) { e.printStackTrace(); }}} }

    輸出量

    Input example... XML encoding: UTF-8 Output stream: This should go to the output.

    1.6輸出

    與org.apache.commons.io.input相似, org.apache.commons.io.output具有OutputStream實現,可以在許多情況下使用。 一個非常有趣的是TeeOutputStream ,它允許將輸出流進行分支,換句話說,我們可以將輸入流發送到2個不同的輸出。

    OutputExample.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 final class OutputExample {private static final String INPUT = "This should go to the output.";public static void runExample() {System.out.println("Output example...");TeeInputStream teeIn = null;TeeOutputStream teeOut = null;try {// TeeOutputStreamByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));ByteArrayOutputStream out1 = new ByteArrayOutputStream();ByteArrayOutputStream out2 = new ByteArrayOutputStream();teeOut = new TeeOutputStream(out1, out2);teeIn = new TeeInputStream(in, teeOut, true);teeIn.read(new byte[INPUT.length()]);System.out.println("Output stream 1: " + out1.toString());System.out.println("Output stream 2: " + out2.toString());} catch (IOException e) {e.printStackTrace();} finally {// No need to close teeOut. When teeIn closes, it will also close its// Output stream (which is teeOut), which will in turn close the 2// branches (out1, out2).try { teeIn.close(); }catch (IOException e) { e.printStackTrace(); }}} }

    輸出量

    Output example... Output stream 1: This should go to the output. Output stream 2: This should go to the output.

    2.下載完整示例

    這是Apache Commons IO的簡介 ,涵蓋了大多數為開發人員提供簡單解決方案的重要類。 這個龐大的軟件包中還有許多其他功能,但是通過使用此介紹,您可以了解將來的項目的總體思路和一些有用的工具!

    下載
    您可以在此處下載此示例的完整源代碼: ApacheCommonsIOExample.rar

    翻譯自: https://www.javacodegeeks.com/2014/10/apache-commons-io-tutorial.html

    總結

    以上是生活随笔為你收集整理的Apache Commons IO教程:初学者指南的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。