apache commons io包快速入门

来源:互联网 发布:mac 图片导出 编辑:程序博客网 时间:2024/04/29 18:51

原文参考 
http://www.javacodegeeks.com/2014/10/apache-commons-io-tutorial.html 

  Apache Commons IO 包绝对是好东西,地址在http://commons.apache.org/proper/commons-io/,下面用例子分别介绍: 
  1)  工具类 
  2) 输入 
  3) 输出 
  4) filters过滤 
  5) Comparators 
  6) 文件监控 
  
   总的入口例子为: 
  

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



一  工具类包UtilityExample代码: 

    这个工具类包分如下几个主要工具类: 
     1) FilenameUtils:主要处理各种操作系统下对文件名的操作 
     2) FileUtils:处理文件的打开,移动,读取和判断文件是否存在 
    3) IOCASE:字符串的比较 
    4) FileSystemUtils:返回磁盘的空间大小 

   
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. import org.apache.commons.io.FileSystemUtils;  
  5. import org.apache.commons.io.FileUtils;  
  6. import org.apache.commons.io.FilenameUtils;  
  7. import org.apache.commons.io.LineIterator;  
  8. import org.apache.commons.io.IOCase;  
  9.   
  10. public final class UtilityExample {  
  11.       
  12.     // We are using the file exampleTxt.txt in the folder ExampleFolder,  
  13.     // and we need to provide the full path to the Utility classes.  
  14.     private static final String EXAMPLE_TXT_PATH =  
  15.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";  
  16.       
  17.     private static final String PARENT_DIR =  
  18.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample";  
  19.   
  20.     public static void runExample() throws IOException {  
  21.         System.out.println("Utility Classes example...");  
  22.           
  23.           
  24.         // FilenameUtils  
  25.           
  26.         System.out.println("Full path of exampleTxt: " +  
  27.                 FilenameUtils.getFullPath(EXAMPLE_TXT_PATH));  
  28.           
  29.         System.out.println("Full name of exampleTxt: " +  
  30.                 FilenameUtils.getName(EXAMPLE_TXT_PATH));  
  31.           
  32.         System.out.println("Extension of exampleTxt: " +  
  33.                 FilenameUtils.getExtension(EXAMPLE_TXT_PATH));  
  34.           
  35.         System.out.println("Base name of exampleTxt: " +  
  36.                 FilenameUtils.getBaseName(EXAMPLE_TXT_PATH));  
  37.           
  38.           
  39.         // FileUtils  
  40.           
  41.         // We can create a new File object using FileUtils.getFile(String)  
  42.         // and then use this object to get information from the file.  
  43.         File exampleFile = FileUtils.getFile(EXAMPLE_TXT_PATH);  
  44.         LineIterator iter = FileUtils.lineIterator(exampleFile);  
  45.           
  46.         System.out.println("Contents of exampleTxt...");  
  47.         while (iter.hasNext()) {  
  48.             System.out.println("\t" + iter.next());  
  49.         }  
  50.         iter.close();  
  51.           
  52.         // We can check if a file exists somewhere inside a certain directory.  
  53.         File parent = FileUtils.getFile(PARENT_DIR);  
  54.         System.out.println("Parent directory contains exampleTxt file: " +  
  55.                 FileUtils.directoryContains(parent, exampleFile));  
  56.           
  57.           
  58.         // IOCase  
  59.           
  60.         String str1 = "This is a new String.";  
  61.         String str2 = "This is another new String, yes!";  
  62.           
  63.         System.out.println("Ends with string (case sensitive): " +  
  64.                 IOCase.SENSITIVE.checkEndsWith(str1, "string."));  
  65.         System.out.println("Ends with string (case insensitive): " +  
  66.                 IOCase.INSENSITIVE.checkEndsWith(str1, "string."));  
  67.           
  68.         System.out.println("String equality: " +  
  69.                 IOCase.SENSITIVE.checkEquals(str1, str2));  
  70.           
  71.           
  72.         // FileSystemUtils  
  73.         System.out.println("Free disk space (in KB): " + FileSystemUtils.freeSpaceKb("C:"));  
  74.         System.out.println("Free disk space (in MB): " + FileSystemUtils.freeSpaceKb("C:") / 1024);  
  75.     }  
  76. }  



输出: 
Java代码  收藏代码
  1. Utility Classes example...  
  2. Full path of exampleTxt: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\  
  3. Full name of exampleTxt: exampleTxt.txt  
  4. Extension of exampleTxt: txt  
  5. Base name of exampleTxt: exampleTxt  
  6. Contents of exampleTxt...  
  7.     This is an example text file.  
  8.     We will use it for experimenting with Apache Commons IO.  
  9. Parent directory contains exampleTxt file: true  
  10. Ends with string (case sensitive): false  
  11. Ends with string (case insensitive): true  
  12. String equality: false  
  13. Free disk space (in KB): 32149292  
  14. Free disk space (in MB): 31395  



二  FileMonitor工具类包 
   这个org.apache.commons.io.monitor 包中的工具类可以监视文件或者目录的变化,获得指定文件或者目录的相关信息,下面看例子: 
  
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3.   
  4. import org.apache.commons.io.FileDeleteStrategy;  
  5. import org.apache.commons.io.FileUtils;  
  6. import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;  
  7. import org.apache.commons.io.monitor.FileAlterationMonitor;  
  8. import org.apache.commons.io.monitor.FileAlterationObserver;  
  9. import org.apache.commons.io.monitor.FileEntry;  
  10.   
  11.   
  12. public final class FileMonitorExample {  
  13.       
  14.     private static final String EXAMPLE_PATH =  
  15.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleFileEntry.txt";  
  16.       
  17.     private static final String PARENT_DIR =  
  18.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
  19.       
  20.     private static final String NEW_DIR =  
  21.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newDir";  
  22.       
  23.     private static final String NEW_FILE =  
  24.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\newFile.txt";  
  25.   
  26.     public static void runExample() {  
  27.         System.out.println("File Monitor example...");  
  28.           
  29.           
  30.         // FileEntry  
  31.           
  32.         // We can monitor changes and get information about files  
  33.         // using the methods of this class.  
  34.         FileEntry entry = new FileEntry(FileUtils.getFile(EXAMPLE_PATH));  
  35.           
  36.         System.out.println("File monitored: " + entry.getFile());  
  37.         System.out.println("File name: " + entry.getName());  
  38.         System.out.println("Is the file a directory?: " + entry.isDirectory());  
  39.           
  40.           
  41.         // File Monitoring  
  42.           
  43.         // Create a new observer for the folder and add a listener  
  44.         // that will handle the events in a specific directory and take action.  
  45.         File parentDir = FileUtils.getFile(PARENT_DIR);  
  46.           
  47.         FileAlterationObserver observer = new FileAlterationObserver(parentDir);  
  48.         observer.addListener(new FileAlterationListenerAdaptor() {  
  49.               
  50.                 @Override  
  51.                 public void onFileCreate(File file) {  
  52.                     System.out.println("File created: " + file.getName());  
  53.                 }  
  54.                   
  55.                 @Override  
  56.                 public void onFileDelete(File file) {  
  57.                     System.out.println("File deleted: " + file.getName());  
  58.                 }  
  59.                   
  60.                 @Override  
  61.                 public void onDirectoryCreate(File dir) {  
  62.                     System.out.println("Directory created: " + dir.getName());  
  63.                 }  
  64.                   
  65.                 @Override  
  66.                 public void onDirectoryDelete(File dir) {  
  67.                     System.out.println("Directory deleted: " + dir.getName());  
  68.                 }  
  69.         });  
  70.           
  71.         // Add a monior that will check for events every x ms,  
  72.         // and attach all the different observers that we want.  
  73.         FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);  
  74.         try {  
  75.             monitor.start();  
  76.           
  77.             // After we attached the monitor, we can create some files and directories  
  78.             // and see what happens!  
  79.             File newDir = new File(NEW_DIR);  
  80.             File newFile = new File(NEW_FILE);  
  81.               
  82.             newDir.mkdirs();  
  83.             newFile.createNewFile();  
  84.                   
  85.             Thread.sleep(1000);  
  86.               
  87.             FileDeleteStrategy.NORMAL.delete(newDir);  
  88.             FileDeleteStrategy.NORMAL.delete(newFile);  
  89.               
  90.             Thread.sleep(1000);  
  91.               
  92.             monitor.stop();  
  93.         } catch (IOException e) {  
  94.             e.printStackTrace();  
  95.         } catch (InterruptedException e) {  
  96.             e.printStackTrace();  
  97.         } catch (Exception e) {  
  98.             e.printStackTrace();  
  99.         }  
  100.     }  
  101. }  

输出如下: 
  
Java代码  收藏代码
  1. File Monitor example...  
  2. File monitored: C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt  
  3. File name: exampleFileEntry.txt  
  4. Is the file a directory?: false  
  5. Directory created: newDir  
  6. File created: newFile.txt  
  7. Directory deleted: newDir  
  8. File deleted: newFile.txt  


    上面的特性的确很赞!分析下,这个工具类包下的工具类,可以允许我们创建跟踪文件或目录变化的监听句柄,当文件目录等发生任何变化,都可以用“观察者”的身份进行观察, 
其步骤如下: 
   1) 创建要监听的文件对象 
   2) 创建FileAlterationObserver 监听对象,在上面的例子中, 
   File parentDir = FileUtils.getFile(PARENT_DIR); 
  FileAlterationObserver observer = new FileAlterationObserver(parentDir); 
   创建的是监视parentDir目录的变化, 
   3) 为观察器创建FileAlterationListenerAdaptor的内部匿名类,增加对文件及目录的增加删除的监听 
   4) 创建FileAlterationMonitor监听类,每隔500ms监听目录下的变化,其中开启监视是用monitor的start方法即可。 

三  过滤器 filters 
   先看例子: 
  
Java代码  收藏代码
  1. import java.io.File;  
  2.   
  3. import org.apache.commons.io.FileUtils;  
  4. import org.apache.commons.io.IOCase;  
  5. import org.apache.commons.io.filefilter.AndFileFilter;  
  6. import org.apache.commons.io.filefilter.NameFileFilter;  
  7. import org.apache.commons.io.filefilter.NotFileFilter;  
  8. import org.apache.commons.io.filefilter.OrFileFilter;  
  9. import org.apache.commons.io.filefilter.PrefixFileFilter;  
  10. import org.apache.commons.io.filefilter.SuffixFileFilter;  
  11. import org.apache.commons.io.filefilter.WildcardFileFilter;  
  12.   
  13. public final class FiltersExample {  
  14.       
  15.     private static final String PARENT_DIR =  
  16.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
  17.   
  18.     public static void runExample() {  
  19.         System.out.println("File Filter example...");  
  20.           
  21.           
  22.         // NameFileFilter  
  23.         // Right now, in the parent directory we have 3 files:  
  24.         //      directory example  
  25.         //      file exampleEntry.txt  
  26.         //      file exampleTxt.txt  
  27.           
  28.         // Get all the files in the specified directory  
  29.         // that are named "example".  
  30.         File dir = FileUtils.getFile(PARENT_DIR);  
  31.         String[] acceptedNames = {"example""exampleTxt.txt"};  
  32.         for (String file: dir.list(new NameFileFilter(acceptedNames, IOCase.INSENSITIVE))) {  
  33.             System.out.println("File found, named: " + file);  
  34.         }  
  35.           
  36.           
  37.         //WildcardFileFilter  
  38.         // We can use wildcards in order to get less specific results  
  39.         //      ? used for 1 missing char  
  40.         //      * used for multiple missing chars  
  41.         for (String file: dir.list(new WildcardFileFilter("*ample*"))) {  
  42.             System.out.println("Wildcard file found, named: " + file);  
  43.         }  
  44.           
  45.           
  46.         // PrefixFileFilter   
  47.         // We can also use the equivalent of startsWith  
  48.         // for filtering files.  
  49.         for (String file: dir.list(new PrefixFileFilter("example"))) {  
  50.             System.out.println("Prefix file found, named: " + file);  
  51.         }  
  52.           
  53.           
  54.         // SuffixFileFilter  
  55.         // We can also use the equivalent of endsWith  
  56.         // for filtering files.  
  57.         for (String file: dir.list(new SuffixFileFilter(".txt"))) {  
  58.             System.out.println("Suffix file found, named: " + file);  
  59.         }  
  60.           
  61.           
  62.         // OrFileFilter   
  63.         // We can use some filters of filters.  
  64.         // in this case, we use a filter to apply a logical   
  65.         // or between our filters.  
  66.         for (String file: dir.list(new OrFileFilter(  
  67.                 new WildcardFileFilter("*ample*"), new SuffixFileFilter(".txt")))) {  
  68.             System.out.println("Or file found, named: " + file);  
  69.         }  
  70.           
  71.         // And this can become very detailed.  
  72.         // Eg, get all the files that have "ample" in their name  
  73.         // but they are not text files (so they have no ".txt" extension.  
  74.         for (String file: dir.list(new AndFileFilter( // we will match 2 filters...  
  75.                 new WildcardFileFilter("*ample*"), // ...the 1st is a wildcard...  
  76.                 new NotFileFilter(new SuffixFileFilter(".txt"))))) { // ...and the 2nd is NOT .txt.  
  77.             System.out.println("And/Not file found, named: " + file);  
  78.         }  
  79.     }  
  80. }  

      可以看清晰看到,使用过滤器,可以分别在指定的目录下,寻找符合条件 
的文件,比如以什么开头的文件名,支持通配符,甚至支持多个过滤器进行或的操作! 
  输出如下: 
 
Java代码  收藏代码
  1. File Filter example...  
  2. File found, named: example  
  3. File found, named: exampleTxt.txt  
  4. Wildcard file found, named: example  
  5. Wildcard file found, named: exampleFileEntry.txt  
  6. Wildcard file found, named: exampleTxt.txt  
  7. Prefix file found, named: example  
  8. Prefix file found, named: exampleFileEntry.txt  
  9. Prefix file found, named: exampleTxt.txt  
  10. Suffix file found, named: exampleFileEntry.txt  
  11. Suffix file found, named: exampleTxt.txt  
  12. Or file found, named: example  
  13. Or file found, named: exampleFileEntry.txt  
  14. Or file found, named: exampleTxt.txt  
  15. And/Not file found, named: example  



四  Comparators比较器 
   org.apache.commons.io.comparator包下的工具类,可以方便进行文件的比较: 
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.util.Date;  
  3.   
  4. import org.apache.commons.io.FileUtils;  
  5. import org.apache.commons.io.IOCase;  
  6. import org.apache.commons.io.comparator.LastModifiedFileComparator;  
  7. import org.apache.commons.io.comparator.NameFileComparator;  
  8. import org.apache.commons.io.comparator.SizeFileComparator;  
  9.   
  10. public final class ComparatorExample {  
  11.       
  12.     private static final String PARENT_DIR =  
  13.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder";  
  14.       
  15.     private static final String FILE_1 =  
  16.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\example";  
  17.       
  18.     private static final String FILE_2 =  
  19.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\ExampleFolder\\exampleTxt.txt";  
  20.       
  21.     public static void runExample() {  
  22.         System.out.println("Comparator example...");  
  23.           
  24.         //NameFileComparator  
  25.           
  26.         // Let's get a directory as a File object  
  27.         // and sort all its files.  
  28.         File parentDir = FileUtils.getFile(PARENT_DIR);  
  29.         NameFileComparator comparator = new NameFileComparator(IOCase.SENSITIVE);  
  30.         File[] sortedFiles = comparator.sort(parentDir.listFiles());  
  31.           
  32.         System.out.println("Sorted by name files in parent directory: ");  
  33.         for (File file: sortedFiles) {  
  34.             System.out.println("\t"+ file.getAbsolutePath());  
  35.         }  
  36.           
  37.           
  38.         // SizeFileComparator  
  39.           
  40.         // We can compare files based on their size.  
  41.         // The boolean in the constructor is about the directories.  
  42.         //      true: directory's contents count to the size.  
  43.         //      false: directory is considered zero size.  
  44.         SizeFileComparator sizeComparator = new SizeFileComparator(true);  
  45.         File[] sizeFiles = sizeComparator.sort(parentDir.listFiles());  
  46.           
  47.         System.out.println("Sorted by size files in parent directory: ");  
  48.         for (File file: sizeFiles) {  
  49.             System.out.println("\t"+ file.getName() + " with size (kb): " + file.length());  
  50.         }  
  51.           
  52.           
  53.         // LastModifiedFileComparator  
  54.           
  55.         // We can use this class to find which file was more recently modified.  
  56.         LastModifiedFileComparator lastModified = new LastModifiedFileComparator();  
  57.         File[] lastModifiedFiles = lastModified.sort(parentDir.listFiles());  
  58.           
  59.         System.out.println("Sorted by last modified files in parent directory: ");  
  60.         for (File file: lastModifiedFiles) {  
  61.             Date modified = new Date(file.lastModified());  
  62.             System.out.println("\t"+ file.getName() + " last modified on: " + modified);  
  63.         }  
  64.           
  65.         // Or, we can also compare 2 specific files and find which one was last modified.  
  66.         //      returns > 0 if the first file was last modified.  
  67.         //      returns  0)  
  68.             System.out.println("File " + file1.getName() + " was modified last because...");  
  69.         else  
  70.             System.out.println("File " + file2.getName() + "was modified last because...");  
  71.           
  72.         System.out.println("\t"+ file1.getName() + " last modified on: " +  
  73.                 new Date(file1.lastModified()));  
  74.         System.out.println("\t"+ file2.getName() + " last modified on: " +  
  75.                 new Date(file2.lastModified()));  
  76.     }  
  77. }  


   输出如下: 
Java代码  收藏代码
  1. Comparator example...  
  2. Sorted by name files in parent directory:   
  3.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comparator1.txt  
  4.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\comperator2.txt  
  5.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\example  
  6.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleFileEntry.txt  
  7.     C:\Users\Lilykos\workspace\ApacheCommonsExample\ExampleFolder\exampleTxt.txt  
  8. Sorted by size files in parent directory:   
  9.     example with size (kb): 0  
  10.     exampleTxt.txt with size (kb): 87  
  11.     exampleFileEntry.txt with size (kb): 503  
  12.     comperator2.txt with size (kb): 1458  
  13.     comparator1.txt with size (kb): 4436  
  14. Sorted by last modified files in parent directory:   
  15.     exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014  
  16.     example last modified on: Sun Oct 26 23:42:55 EET 2014  
  17.     comparator1.txt last modified on: Tue Oct 28 14:48:28 EET 2014  
  18.     comperator2.txt last modified on: Tue Oct 28 14:48:52 EET 2014  
  19.     exampleFileEntry.txt last modified on: Tue Oct 28 14:53:50 EET 2014  
  20. File example was modified last because...  
  21.     example last modified on: Sun Oct 26 23:42:55 EET 2014  
  22.     exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014  



    可以看到,在上面的代码中 
NameFileComparator: 文件名的比较器,可以进行文件名称排序; 
SizeFileComparator: 按照文件大小比较 
LastModifiedFileComparator: 根据最新修改日期比较 

五  input包 
    在 common io的org.apache.commons.io.input 包中,有各种对InputStream的实现类: 
我们看下其中的TeeInputStream, ,它接受InputStream和Outputstream参数,例子如下: 
  
Java代码  收藏代码
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.io.FileUtils;  
  7. import org.apache.commons.io.input.TeeInputStream;  
  8. import org.apache.commons.io.input.XmlStreamReader;  
  9.   
  10.   
  11. public final class InputExample {  
  12.       
  13.     private static final String XML_PATH =  
  14.             "C:\\Users\\Lilykos\\workspace\\ApacheCommonsExample\\InputOutputExampleFolder\\web.xml";  
  15.       
  16.     private static final String INPUT = "This should go to the output.";  
  17.   
  18.     public static void runExample() {  
  19.         System.out.println("Input example...");  
  20.         XmlStreamReader xmlReader = null;  
  21.         TeeInputStream tee = null;  
  22.           
  23.         try {  
  24.               
  25.             // XmlStreamReader  
  26.               
  27.             // We can read an xml file and get its encoding.  
  28.             File xml = FileUtils.getFile(XML_PATH);  
  29.               
  30.             xmlReader = new XmlStreamReader(xml);  
  31.             System.out.println("XML encoding: " + xmlReader.getEncoding());  
  32.               
  33.               
  34.             // TeeInputStream  
  35.               
  36.             // This very useful class copies an input stream to an output stream  
  37.             // and closes both using only one close() method (by defining the 3rd  
  38.             // constructor parameter as true).  
  39.             ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));  
  40.             ByteArrayOutputStream out = new ByteArrayOutputStream();  
  41.               
  42.             tee = new TeeInputStream(in, out, true);  
  43.             tee.read(new byte[INPUT.length()]);  
  44.   
  45.             System.out.println("Output stream: " + out.toString());           
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.         } finally {  
  49.             try { xmlReader.close(); }  
  50.             catch (IOException e) { e.printStackTrace(); }  
  51.               
  52.             try { tee.close(); }  
  53.             catch (IOException e) { e.printStackTrace(); }  
  54.         }  
  55.     }  
  56. }  


输出: 
  
Java代码  收藏代码
  1. Input example...  
  2. XML encoding: UTF-8  
  3. Output stream: This should go to the output.  

   tee = new TeeInputStream(in, out, true); 
   中,分别三个参数,将输入流的内容输出到输出流,true参数为最后关闭流 
六 output工具类包 
  
  其中的org.apache.commons.io.output 是实现了outputstream,其中好特别的是 
TeeOutputStream能将一个输入流分别输出到两个输出流 
  
Java代码  收藏代码
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4.   
  5. import org.apache.commons.io.input.TeeInputStream;  
  6. import org.apache.commons.io.output.TeeOutputStream;  
  7.   
  8. public final class OutputExample {  
  9.       
  10.     private static final String INPUT = "This should go to the output.";  
  11.   
  12.     public static void runExample() {  
  13.         System.out.println("Output example...");  
  14.         TeeInputStream teeIn = null;  
  15.         TeeOutputStream teeOut = null;  
  16.           
  17.         try {  
  18.               
  19.             // TeeOutputStream  
  20.               
  21.             ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));  
  22.             ByteArrayOutputStream out1 = new ByteArrayOutputStream();  
  23.             ByteArrayOutputStream out2 = new ByteArrayOutputStream();  
  24.               
  25.             teeOut = new TeeOutputStream(out1, out2);  
  26.             teeIn = new TeeInputStream(in, teeOut, true);  
  27.             teeIn.read(new byte[INPUT.length()]);  
  28.   
  29.             System.out.println("Output stream 1: " + out1.toString());  
  30.             System.out.println("Output stream 2: " + out2.toString());  
  31.               
  32.         } catch (IOException e) {  
  33.             e.printStackTrace();  
  34.         } finally {  
  35.             // No need to close teeOut. When teeIn closes, it will also close its  
  36.             // Output stream (which is teeOut), which will in turn close the 2  
  37.             // branches (out1, out2).  
  38.             try { teeIn.close(); }  
  39.             catch (IOException e) { e.printStackTrace(); }  
  40.         }  
  41.     }  
  42. }  


  输出: 
Java代码  收藏代码
  1. Output example...  
  2. Output stream 1: This should go to the output.  
  3. Output stream 2: This should go to the output.  


完整代码下载:http://a3ab771892fd198a96736e50.javacodegeeks.netdna-cdn.com/wp-content/uploads/2014/10/ApacheCommonsIOExample.rar





原创粉丝点击