Apache Commons IO入門教程(轉)

 

Apache Commons IO是Apache基金會建立並維護的Java函數庫。它提供了許多類使得開發者的常見任務變得簡單,同時減小重複(boiler-plate)代碼,這些代碼可能遍及於每一個獨立的項目中,你卻不得不重複的編寫。這些類由經驗豐富的開發者維護,對各類問題的邊界條件考慮周到,並持續修復相關bug。html

在下面的例子中,咱們會向你演示一些不一樣功能的方法,這些功能都是在org.apache.commons.io包下。Apache Commons IO 是一個巨大工程,咱們不會深刻去剖析它的底層原理,可是會演示一些比較經常使用的例子,無論你是否是新手,相信這些例子都會對你有所幫助。java

1. Apache Commons IO 示例

咱們分別會用幾段代碼來演示下面的功能,每部分功能都表明Apache Commons IO所覆蓋的一個單獨領域,具體以下:web

  • 工具類
  • 輸入
  • 輸出
  • 過濾器
  • 比較器
  • 文件監控器
 

爲了更方便讀者進行理解,咱們會把建立的每一個類的輸出進行單獨展現。而且會把示例中功能演示所用到的到文件放到工程目錄(ExampleFolder目錄)中。apache

注意:爲了能使用org.apache.commons.io中的功能,你首先須要下載jar包(請點擊這裏),而且將jar包添加到Eclipse工程的編譯路徑下,右鍵點工程文件夾 ->  Build Path -> Add external archives。windows

ApacheCommonsExampleMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ApacheCommonsExampleMain {
 
     public static void main(String[] args) {
         UtilityExample.runExample();
 
         FileMonitorExample.runExample();
 
         FiltersExample.runExample();
 
         InputExample.runExample();
 
         OutputExample.runExample();
 
         ComparatorExample.runExample();
     }
}
 
 

這個main方法會運行全部的示例,你能夠將其餘行的代碼註釋來執行你想要的示例。api

1.1 Utility Classes

 
org.apache.commons.io包中有不少工具類,裏面多數類都是完成文件操做以及字符串比較的功能,下面列舉了一下經常使用的工具類:  FilenameUtils 這個工具類是用來處理文件名(譯者注:包含文件路徑)的,他能夠輕鬆解決不一樣操做系統文件名稱規範不一樣的問題(好比windows和Unix)(在Unix系統以及Linux系統中文件分隔符是「/」,不支持」\「,windows中支持」\「以及」/「)。

 

  FileUtils提供文件操做(移動文件,讀取文件,檢查文件是否存在等等)的方法。   IOCase提供字符串操做以及比較的方法。
  FileSystemUtils:提供查看指定目錄剩餘空間的方法。
 
UtilityExample.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleTxt.txt" ;
 
     private static final String PARENT_DIR =
             "C:UsersLilykosworkspaceApacheCommonsExample" ;
 
     public static void runExample() throws IOException {
         System.out.println( "Utility Classes example..." );
 
         // FilenameUtils
 
         System.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));
 
         // IOCase
 
         String 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));
 
         // FileSystemUtils
         System.out.println( "Free disk space (in KB): " + FileSystemUtils.freeSpaceKb( "C:" ));
         System.out.println( "Free disk space (in MB): " + FileSystemUtils.freeSpaceKb( "C:" ) / 1024 );
     }
}
輸出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Utility Classes example...
Full path of exampleTxt: C:UsersLilykosworkspaceApacheCommonsExampleExampleFolder
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包下的類包含的方法能夠獲取文件的指定信息,不過更重要的是,它能夠建立處理器(handler)來跟蹤指定文件或目錄的變化而且能夠在文件或目錄發生變化的時候進行一些操做。讓咱們來看看下面的代碼:app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleFileEntry.txt" ;
 
     private static final String PARENT_DIR =
             "C:UsersLilykosworkspaceApacheCommonsExampleExampleFolder" ;
 
     private static final String NEW_DIR =
             "C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldernewDir" ;
 
     private static final String NEW_FILE =
             "C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldernewFile.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() {
 
                 @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());
                 }
 
                 @Override
                 public void onDirectoryCreate(File dir) {
                     System.out.println( "Directory created: " + dir.getName());
                 }
 
                 @Override
                 public 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();
         }
     }
}
輸出
1
2
3
4
5
6
7
8
File Monitor example...
File monitored: C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleFileEntry.txt
File name: exampleFileEntry.txt
Is the file a directory?: false
Directory created: newDir
File created: newFile.txt
Directory deleted: newDir
File deleted: newFile.tx
讓咱們來看看這裏發生了什麼,咱們使用org.apache.commons.io.monitor包下的類建立了一個處理器來監聽一些特定的事件(在上面的例子中就是咱們對文件或目錄所作的全部操做事件),爲了得到這些信息,咱們須要作如下幾步操做:
一、建立一個File對象,這個對象指向咱們須要監聽變化的目錄。
二、建立一個FileAlterationObserver對象,這個對象會觀察這些變化。
三、經過調用addListener()方法,爲observer對象添加一個 FileAlterationListenerAdaptor對象。你能夠經過不少種方式來建立一個適配器,在咱們的例子中咱們使用內部類的方式進行建立而且只實現其中的一部分方法(只須要實現咱們例子中須要用的方法便可)。

四、建立一個FileAlterationMonitor 對象,將已經建立好的observer對象添加其中而且傳入時間間隔參數(單位是毫秒)。less

五、調用start()方法便可開啓監視器,若是你想中止監視器,調用stop()方法便可。

1.3 過濾器

過濾器能夠以組合的方式使用而且它的用途很是多樣。它能夠輕鬆的區分不一樣的文件而且找到知足咱們條件的文件。咱們能夠組合不一樣的過濾器來執行文件的邏輯比較而且精確的獲取咱們所須要文件,而無需使用冗餘的字符串比較來尋找咱們的文件。eclipse

FiltersExample.javaide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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:UsersLilykosworkspaceApacheCommonsExampleExampleFolder" ;
 
     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 chars
         for (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);
相關文章
相關標籤/搜索