Apache Commons-io工具类的使用

一、工具类

工具类包括FileUtils、IOUtils、FilenameUtils和FileSystemUtils,前三者的方法并没有多大的区别,只是操作的对象不同,故名思议:FileUtils主要操作File类,IOUtils主要操作IO流,FilenameUtils则是操作文件名,FileSystemUtils包含了一些JDK没有提供的用于访问文件系统的实用方法。当前,只有一个用于读取硬盘空余空间的方法可用。实例如下

FileUtils的使用:

[java]  view plain  copy
 print ?
  1. package com.wj.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.List;  
  6.   
  7. import org.apache.commons.io.FileUtils;  
  8. import org.junit.After;  
  9. import org.junit.Before;  
  10. import org.junit.Test;  
  11.   
  12. public class FileUtilsTest {  
  13.   
  14.     private String basePath = null;  
  15.   
  16.     @Before  
  17.     public void setUp() {  
  18.         basePath = System.getProperty("user.dir") + "\\file\\";  
  19.     }  
  20.   
  21.     @After  
  22.     public void tearDown() throws Exception {  
  23.     }  
  24.   
  25.     /** 
  26.      * 拷贝文件 
  27.      * @throws IOException 
  28.      */  
  29.     @Test  
  30.     public void testCopy() throws IOException {  
  31.         File srcFile = new File(basePath + "a.txt");  
  32.         File destFile = new File(basePath + "b.txt");  
  33.         FileUtils.copyFile(srcFile, destFile);  
  34.     }  
  35.       
  36.     /** 
  37.      * 删除文件 
  38.      * @throws IOException 
  39.      */  
  40.     @Test  
  41.     public void testDelete() throws IOException{  
  42.         File delFile = new File(basePath + "b.txt");  
  43.         FileUtils.forceDelete(delFile);  
  44.         //FileUtils.forceMkdir(delFile);  
  45.     }  
  46.       
  47.     /** 
  48.      * 比较文件内容 
  49.      * @throws IOException 
  50.      */  
  51.     @Test  
  52.     public void testCompareFile() throws IOException{  
  53.         File srcFile = new File(basePath + "a.txt");  
  54.         File destFile = new File(basePath + "b.txt");  
  55.         boolean result = FileUtils.contentEquals(srcFile, destFile);  
  56.         System.out.println(result);  
  57.     }  
  58.       
  59.     /** 
  60.      * 移动文件 
  61.      * @throws IOException 
  62.      */  
  63.     @Test  
  64.     public void testMoveFile() throws IOException{  
  65.         File srcFile = new File(basePath + "b.txt");  
  66.         File destDir = new File(basePath + "move");  
  67.         FileUtils.moveToDirectory(srcFile, destDir, true);  
  68.     }  
  69.       
  70.     /** 
  71.      * 读取文件内容 
  72.      * @throws IOException 
  73.      */  
  74.     @Test   
  75.     public void testRead() throws IOException{  
  76.         File srcFile = new File(basePath + "a.txt");  
  77.         String content = FileUtils.readFileToString(srcFile);  
  78.         List<String> contents = FileUtils.readLines(srcFile);  
  79.         System.out.println(content);  
  80.         System.out.println("******************");  
  81.         for (String string : contents) {  
  82.             System.out.println(string);  
  83.         }  
  84.     }  
  85.       
  86.     /** 
  87.      * 写入文件内容 
  88.      * @throws IOException 
  89.      */  
  90.     @Test  
  91.     public void testWrite() throws IOException{  
  92.         File srcFile = new File(basePath + "a.txt");  
  93.         FileUtils.writeStringToFile(srcFile, "\nyes文件"true);  
  94.     }  
  95.       
  96. }  


FileSystemUtils的使用:
[java]  view plain  copy
 print ?
  1. package com.wj.test;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.apache.commons.io.FileSystemUtils;  
  6. import org.junit.After;  
  7. import org.junit.Before;  
  8. import org.junit.Test;  
  9.   
  10. public class FileSystemUtilsTest {  
  11.     @Before  
  12.     public void setUp() throws Exception {  
  13.     }  
  14.   
  15.     @After  
  16.     public void tearDown() throws Exception {  
  17.     }  
  18.   
  19.     /** 
  20.      * 获取磁盘空余空间 
  21.      * @throws IOException 
  22.      */  
  23.     @SuppressWarnings("deprecation")  
  24.     @Test  
  25.     public void testFreeSpace() throws IOException {  
  26.         // 以字节为单位  
  27.         System.out.println(FileSystemUtils.freeSpace("c:\\") / 1024 / 1024 / 1024);  
  28.         System.out.println(FileSystemUtils.freeSpace("d:\\") / 1024 / 1024 / 1024);  
  29.         // 以k为单位  
  30.         System.out.println(FileSystemUtils.freeSpaceKb("e:\\") / 1024 / 1024);  
  31.         System.out.println(FileSystemUtils.freeSpaceKb("f:\\") / 1024 / 1024);  
  32.           
  33.     }  
  34.   
  35. }  

二、尾端类

不同的计算机体系结构使用不同约定的字节排序。在所谓的“低位优先”体系结构中(如Intel),低位字节处于内存中最低位置,而其后的字节,则处于更高的位置。在“高位优先”的体系结构中(如Motorola),这种情况恰恰相反。

这个类库上有两个相关类:

EndianUtils包含用于交换java原对象和流之间的字节序列。

SwappedDataInputStream类是DataInput接口的一个实例。使用它,可以读取非本地的字节序列。


三、行迭代器

org.apache.commons.io.LineIterator类提供了一个灵活的方式与基于行的文件交互。可以直接创建一个实例,或者使用FileUtils或IOUtils的工厂方法来创建,实例如下:

[java]  view plain  copy
 print ?
  1. package com.wj.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.io.FileUtils;  
  7. import org.apache.commons.io.LineIterator;  
  8. import org.junit.After;  
  9. import org.junit.Before;  
  10. import org.junit.Test;  
  11.   
  12. public class LineIteratorTest {  
  13.       
  14.     private String basePath = null;  
  15.   
  16.     @Before  
  17.     public void setUp() throws Exception {  
  18.         basePath = System.getProperty("user.dir") + "\\file\\";  
  19.     }  
  20.   
  21.     @After  
  22.     public void tearDown() throws Exception {  
  23.     }  
  24.       
  25.     /** 
  26.      * 测试行迭代器 
  27.      * @throws IOException 
  28.      */  
  29.     @Test  
  30.     public void testIterator() throws IOException{  
  31.         File file = new File(basePath + "a.txt");  
  32.         LineIterator li = FileUtils.lineIterator(file);  
  33.         while(li.hasNext()){  
  34.             System.out.println(li.nextLine());  
  35.         }  
  36.         LineIterator.closeQuietly(li);  
  37.     }  
  38.   
  39. }  


四、文件过滤器

org.apache.commons.io.filefilter包定义了一个合并了java.io.FileFilter以及java.io.FilenameFilter的接口(IOFileFilter)。除此之外,这个包还提供了一系列直接可用的IOFileFilter的实现类,可以通过他们合并其它的文件过滤器。比如,这些文件过滤器可以在列出文件时使用或者在使用文件对话框时使用。实例如下:

[java]  view plain  copy
 print ?
  1. package com.wj.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.io.filefilter.EmptyFileFilter;  
  7. import org.apache.commons.io.filefilter.SuffixFileFilter;  
  8. import org.junit.After;  
  9. import org.junit.Before;  
  10. import org.junit.Test;  
  11.   
  12. public class FileFilterTest {  
  13.       
  14.     private String basePath = null;  
  15.   
  16.     @Before  
  17.     public void setUp() throws Exception {  
  18.         basePath = System.getProperty("user.dir") + "\\file\\";  
  19.     }  
  20.   
  21.     @After  
  22.     public void tearDown() throws Exception {  
  23.     }  
  24.       
  25.     /** 
  26.      * 空内容文件过滤器 
  27.      * @throws IOException 
  28.      */  
  29.     @Test  
  30.     public void testEmptyFileFilter() throws IOException{  
  31.         File dir = new File(basePath);  
  32.         String[] files = dir.list(EmptyFileFilter.NOT_EMPTY);  
  33.         for (String file : files) {  
  34.             System.out.println(file);  
  35.         }  
  36.     }  
  37.       
  38.     /** 
  39.      * 文件名称后缀过滤器 
  40.      * @throws IOException 
  41.      */  
  42.     @Test  
  43.     public void testSuffixFileFilter() throws IOException{  
  44.         File dir = new File(basePath);  
  45.         String[] files = dir.list(new SuffixFileFilter("a.txt"));  
  46.         for (String file : files) {  
  47.             System.out.println(file);  
  48.         }  
  49.     }  
  50.   
  51. }  



五、文件比较器

org.apache.commons.io.comparator包为java.io.File提供了一些java.util.Comparator接口的实现。例如,可以使用这些比较器对文件集合或数组进行排序。实例如下:

[java]  view plain  copy
 print ?
  1. package com.wj.test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.io.comparator.CompositeFileComparator;  
  7. import org.apache.commons.io.comparator.DirectoryFileComparator;  
  8. import org.apache.commons.io.comparator.NameFileComparator;  
  9. import org.apache.commons.io.comparator.PathFileComparator;  
  10. import org.junit.After;  
  11. import org.junit.Before;  
  12. import org.junit.Test;  
  13.   
  14. public class ComparatorTest {  
  15.   
  16.     private String basePath = null;  
  17.   
  18.     @Before  
  19.     public void setUp() throws Exception {  
  20.         basePath = System.getProperty("user.dir") + "\\file\\";  
  21.     }  
  22.   
  23.     @After  
  24.     public void tearDown() throws Exception {  
  25.     }  
  26.   
  27.     /** 
  28.      * 文件名称比较器 
  29.      * @throws IOException 
  30.      */  
  31.     @Test  
  32.     public void testNameFileComparator() throws IOException {  
  33.         File f1 = new File(basePath + "a.txt");  
  34.         File f2 = new File(basePath + "c.txt");  
  35.         int result = NameFileComparator.NAME_COMPARATOR.compare(f1, f2);  
  36.         System.out.println(result);  
  37.     }  
  38.   
  39.     /** 
  40.      * 文件路径比较器 
  41.      * @throws IOException 
  42.      */  
  43.     @Test  
  44.     public void testPathFileComparator() throws IOException {  
  45.         File f1 = new File(basePath + "a.txt");  
  46.         File f2 = new File(basePath + "c.txt");  
  47.         int result = PathFileComparator.PATH_COMPARATOR.compare(f1, f2);  
  48.         System.out.println(result);  
  49.     }  
  50.   
  51.     /** 
  52.      * 组合比较器 
  53.      * @throws IOException 
  54.      */  
  55.     @SuppressWarnings("unchecked")  
  56.     @Test  
  57.     public void testCompositeFileComparator() throws IOException {  
  58.         File dir = new File(basePath);  
  59.         File [] files = dir.listFiles();  
  60.         for (File file : files) {  
  61.             System.out.println(file.getName());  
  62.         }  
  63.         CompositeFileComparator cfc = new CompositeFileComparator(  
  64.                 DirectoryFileComparator.DIRECTORY_COMPARATOR,  
  65.                 NameFileComparator.NAME_COMPARATOR);  
  66.         cfc.sort(files);  
  67.         System.out.println("*****after sort*****");  
  68.         for (File file : files) {  
  69.             System.out.println(file.getName());  
  70.         }  
  71.     }  
  72. }  

六、扩展流

org.apache.commons.io.input和org.apache.commons.io.output包中包含的针对数据流的各种各样的的实现。包括:

  • 空输出流-默默吸收发送给它的所有数据
  • T型输出流-全用两个输出流替换一个进行发送
  • 字节数组输出流-这是一个更快版本的JDK类
  • 计数流-计算通过的字节数
  • 代理流-使用正确的方法委拖
  • 可锁写入-使用上锁文件提供同步写入

  • 等等
七、FileUtils、IOUtils工具的使用实例
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // by FileUtils    
  2. List<String> lines = FileUtils.readLines(file, "UTF-8");    
  3.     
  4. // by IOUtils    
  5. List<String> lines = IOUtils.readLines(new FileInputStream(file), "UTF-8");    
[html]  view plain  copy
  1. // by FileUtils    
  2. List<String> lines = FileUtils.readLines(file, "UTF-8");    
  3.     
  4. // by IOUtils    
  5. List<String> lines = IOUtils.readLines(new FileInputStream(file), "UTF-8");    


写入文件:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // by FileUtils    
  2. FileUtils.writeLines(file, "UTF-8", lines);    
  3.     
  4. // by IOUtils    
  5. IOUtils.writeLines(lines, null, new FileOutputStream(file));    
[html]  view plain  copy
  1. // by FileUtils    
  2. FileUtils.writeLines(file, "UTF-8", lines);    
  3.     
  4. // by IOUtils    
  5. IOUtils.writeLines(lines, null, new FileOutputStream(file));    


 


[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class IoTest {    
  2.     
  3.     /**  
  4.      * @param args  
  5.      */    
  6.     public static void main(String[] args) throws Exception {    
  7.         // 输入流复制到 输出流   
  8.         Writer write = new FileWriter("c:\\kk.dat");    
  9.     
  10.         InputStream ins = new FileInputStream(new File("c:\\text.txt"));    
  11.     
  12.         IOUtils.copy(ins, write);    
  13.         write.close();    
  14.     
  15.         ins.close();    
  16.           
  17.         //文本写入指定文件   
  18.         String name = "my name is panxiuyan";    
  19.             
  20.         File file =  new File("c:\\name.txt");    
  21.             
  22.         FileUtils.writeStringToFile(file, name);    
  23.           
  24.         //将输入流转换成文本   
  25.           
  26.         URL url = new URL("http://www.dimurmill.com");    
  27.             
  28.         InputStream ins = url.openStream();    
  29.             
  30.         String contents = IOUtils.toString(ins,"UTF-8");    
  31.         System.out.println( "Slashdot: " + contents );    
  32.     
  33.             //关闭相关流  
  34.              File file = null;    
  35.             
  36.         InputStream ins = null;    
  37.         try{    
  38.             file = new File("C:\\Test.java");    
  39.                 
  40.             ins = new FileInputStream(file);    
  41.         }catch(Exception e){    
  42.             e.printStackTrace();    
  43.         }finally{    
  44.             IOUtils.closeQuietly(ins);    
  45.         }    
  46.     
  47.           
  48.         }  
  49.           
  50.         //文件复制  
  51.         File srcfile = new File("c:\\Test.java");      
  52.         File destfile = new File("c:\\Test.java.bak");      
  53.         FileUtils.copyFile(srcfile, destfile);      
  54.       
  55.         //文件复制指定的目录   
  56.         File srcfile = new File("c:\\Test.java");      
  57.         File destDir = new File("D:\\");    
  58.         FileUtils.copyFileToDirectory(srcfile, destDir);    
  59.       
  60.         //网络流保存为文件  
  61.     URL url = new URL("http://www.163.com");     
  62.         File file = new File("c:\\163.html");        
  63.         FileUtils.copyURLToFile(url, file);    
  64.           
  65.         //文件目录操作   
  66.         File dir = new File("c:\\test");    
  67.         FileUtils.cleanDirectory(dir);//清空目录下的文件    
  68.         FileUtils.deleteDirectory(dir);//删除目录和目录下的文件   
  69.           
  70.         //目录大小    
  71.         long size = FileUtils.sizeOfDirectory(dir);    
  72.           
  73.         //目录操作  
  74.         File testFile = new File( "testFile.txt" );    
  75.         //如果不存在,新建    
  76.         // 如果存在,修改文件修改时间    
  77.         FileUtils.touch( testFile );    
  78.         //记录流的读取写入字节数   
  79.         File test = new File( "test.dat" );    
  80.         //输出流的统计    
  81.     CountingOutputStream countStream = null;    
  82.     //输入流的统计    
  83.     //CountingInputStream countStream = null;    
  84.     try {    
  85.             FileOutputStream fos = new FileOutputStream( test );            
  86.         countStream = new CountingOutputStream( fos );    
  87.         countStream.write( "Hello".getBytes( ) );    
  88.         } catch( IOException ioe ) {    
  89.             System.out.println( "Error writing bytes to file." );    
  90.         } finally {         
  91.             IOUtils.closeQuietly( countStream );      
  92.         }    
  93.                     
  94.         if( countStream != null ) {    
  95.              int bytesWritten = countStream.getCount( );    
  96.              System.out.println( "Wrote " + bytesWritten + " bytes to test.dat" );    
  97.         }    
  98.                   
  99.         //相同的内容写入不同的文本   
  100.         File test1 = new File("split1.txt");    
  101.                 File test2 = new File("split2.txt");    
  102.         OutputStream outStream = null;    
  103.         try {    
  104.             FileOutputStream fos1 = new FileOutputStream( test1 );    
  105.             FileOutputStream fos2 = new FileOutputStream( test2 );    
  106.             //包含不同的文本    
  107.             outStream = new TeeOutputStream( fos1, fos2 );    
  108.             outStream.write( "One Two Three, Test".getBytes( ) );    
  109.             outStream.flush( );         
  110.         } catch( IOException ioe ) {        
  111.             System.out.println( "Error writing to split output stream" );           
  112.         } finally {             
  113.             IOUtils.closeQuietly( outStream );              
  114.             }   
  115.          }    
  116.     
  117. }    
[java]  view plain  copy
  1. public class IoTest {    
  2.     
  3.     /**  
  4.      * @param args  
  5.      */    
  6.     public static void main(String[] args) throws Exception {    
  7.         // 输入流复制到 输出流   
  8.         Writer write = new FileWriter("c:\\kk.dat");    
  9.     
  10.         InputStream ins = new FileInputStream(new File("c:\\text.txt"));    
  11.     
  12.         IOUtils.copy(ins, write);    
  13.         write.close();    
  14.     
  15.         ins.close();    
  16.           
  17.         //文本写入指定文件   
  18.         String name = "my name is panxiuyan";    
  19.             
  20.         File file =  new File("c:\\name.txt");    
  21.             
  22.         FileUtils.writeStringToFile(file, name);    
  23.           
  24.         //将输入流转换成文本   
  25.           
  26.         URL url = new URL("http://www.dimurmill.com");    
  27.             
  28.         InputStream ins = url.openStream();    
  29.             
  30.         String contents = IOUtils.toString(ins,"UTF-8");    
  31.         System.out.println( "Slashdot: " + contents );    
  32.     
  33.             //关闭相关流  
  34.              File file = null;    
  35.             
  36.         InputStream ins = null;    
  37.         try{    
  38.             file = new File("C:\\Test.java");    
  39.                 
  40.             ins = new FileInputStream(file);    
  41.         }catch(Exception e){    
  42.             e.printStackTrace();    
  43.         }finally{    
  44.             IOUtils.closeQuietly(ins);    
  45.         }    
  46.     
  47.           
  48.         }  
  49.           
  50.         //文件复制  
  51.         File srcfile = new File("c:\\Test.java");      
  52.         File destfile = new File("c:\\Test.java.bak");      
  53.         FileUtils.copyFile(srcfile, destfile);      
  54.       
  55.         //文件复制指定的目录   
  56.         File srcfile = new File("c:\\Test.java");      
  57.         File destDir = new File("D:\\");    
  58.         FileUtils.copyFileToDirectory(srcfile, destDir);    
  59.       
  60.         //网络流保存为文件  
  61.     URL url = new URL("http://www.163.com");     
  62.         File file = new File("c:\\163.html");        
  63.         FileUtils.copyURLToFile(url, file);    
  64.           
  65.         //文件目录操作   
  66.         File dir = new File("c:\\test");    
  67.         FileUtils.cleanDirectory(dir);//清空目录下的文件    
  68.         FileUtils.deleteDirectory(dir);//删除目录和目录下的文件   
  69.           
  70.         //目录大小    
  71.         long size = FileUtils.sizeOfDirectory(dir);    
  72.           
  73.         //目录操作  
  74.         File testFile = new File( "testFile.txt" );    
  75.         //如果不存在,新建    
  76.         // 如果存在,修改文件修改时间    
  77.         FileUtils.touch( testFile );    
  78.         //记录流的读取写入字节数   
  79.         File test = new File( "test.dat" );    
  80.         //输出流的统计    
  81.     CountingOutputStream countStream = null;    
  82.     //输入流的统计    
  83.     //CountingInputStream countStream = null;    
  84.     try {    
  85.             FileOutputStream fos = new FileOutputStream( test );            
  86.         countStream = new CountingOutputStream( fos );    
  87.         countStream.write( "Hello".getBytes( ) );    
  88.         } catch( IOException ioe ) {    
  89.             System.out.println( "Error writing bytes to file." );    
  90.         } finally {         
  91.             IOUtils.closeQuietly( countStream );      
  92.         }    
  93.                     
  94.         if( countStream != null ) {    
  95.              int bytesWritten = countStream.getCount( );    
  96.              System.out.println( "Wrote " + bytesWritten + " bytes to test.dat" );    
  97.         }    
  98.                   
  99.         //相同的内容写入不同的文本   
  100.         File test1 = new File("split1.txt");    
  101.                 File test2 = new File("split2.txt");    
  102.         OutputStream outStream = null;    
  103.         try {    
  104.             FileOutputStream fos1 = new FileOutputStream( test1 );    
  105.             FileOutputStream fos2 = new FileOutputStream( test2 );    
  106.             //包含不同的文本    
  107.             outStream = new TeeOutputStream( fos1, fos2 );    
  108.             outStream.write( "One Two Three, Test".getBytes( ) );    
  109.             outStream.flush( );         
  110.         } catch( IOException ioe ) {        
  111.             System.out.println( "Error writing to split output stream" );           
  112.         } finally {             
  113.             IOUtils.closeQuietly( outStream );              
  114.             }   
  115.          }    
  116.     
  117. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值