commons-io是一款处理io流的工具,封装了很多处理io流和文件的方法,可以大大简化我们处理io流和操作文件的代码。从common-io的官方使用文档可以看出,它主要分为工具类、尾端类、行迭代器、文件过滤器、文件比较器和扩展流。

官网地址:http://commons.apache.org/proper/commons-io/

下载 :http://commons.apache.org/proper/commons-io/download_io.cgi

一、工具类

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

FileUtils的使用:

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

FileSystemUtils的使用:

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

二、尾端类

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

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

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

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

三、行迭代器

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

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

四、文件过滤器

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

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

五、文件比较器

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

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

六、扩展流

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

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

【跟我学apache-commons】【四】commons-io的使用的更多相关文章

  1. HTTP Status 500 - org.apache.jasper.JasperException: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException

    HTTP Status 500 - org.apache.jasper.JasperException: com.sun.org.apache.xerces.internal.impl.io.Malf ...

  2. com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte

    com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte ...

  3. com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 3 字节的 UTF-8 序列的字节 3 无效。

    org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document fro ...

  4. [老老实实学WCF] 第四篇 初探通信--ChannelFactory

    老老实实学WCF 第四篇 初探通信--ChannelFactory 通过前几篇的学习,我们简单了解了WCF的服务端-客户端模型,可以建立一个简单的WCF通信程序,并且可以把我们的服务寄宿在IIS中了. ...

  5. 一步一步学ZedBoard & Zynq(四):基于AXI Lite 总线的从设备IP设计

    本帖最后由 xinxincaijq 于 2013-1-9 10:27 编辑 一步一步学ZedBoard & Zynq(四):基于AXI Lite 总线的从设备IP设计 转自博客:http:// ...

  6. 从零开始学Xamarin.Forms(四) Android 准备步骤(添加第三方Xamarin.Forms.Labs库)

    原文:从零开始学Xamarin.Forms(四) Android 准备步骤(添加第三方Xamarin.Forms.Labs库)  1.安装对应dll     Update-Package Xama ...

  7. 【原创】大叔问题定位分享(16)spark写数据到hive外部表报错ClassCastException: org.apache.hadoop.hive.hbase.HiveHBaseTableOutputFormat cannot be cast to org.apache.hadoop.hive.ql.io.HiveOutputFormat

    spark 2.1.1 spark在写数据到hive外部表(底层数据在hbase中)时会报错 Caused by: java.lang.ClassCastException: org.apache.h ...

  8. (素材源代码)猫猫学IOS(四)UI之半小时搞定Tom猫

    下载地址:http://download.csdn.net/detail/u013357243/8514915 以下是执行图片展示 制作思路以及代码解析 猫猫学IOS(四)UI之半小时搞定Tom猫这里 ...

  9. hive orc压缩数据异常java.lang.ClassCastException: org.apache.hadoop.io.Text cannot be cast to org.apache.hadoop.hive.ql.io.orc.OrcSerde$OrcSerdeRow

    hive表在创建时候指定存储格式 STORED AS ORC tblproperties ('orc.compress'='SNAPPY'); 当insert数据到表时抛出异常 Caused by: ...

  10. HDU 6467 简单数学题 【递推公式 && O(1)优化乘法】(广东工业大学第十四届程序设计竞赛)

    传送门:http://acm.hdu.edu.cn/showproblem.php?pid=6467 简单数学题 Time Limit: 4000/2000 MS (Java/Others)    M ...

随机推荐

  1. [LOJ#2878]. 「JOISC 2014 Day2」邮戳拉力赛[括号序列dp]

    题意 题目链接 分析 如果走到了下行车站就一定会在前面的某个车站走回上行车站,可以看成是一对括号. 我们要求的就是 类似 代价最小的括号序列匹配问题,定义 f(i,j) 表示到 i 有 j 个左括号没 ...

  2. .NetCore利用BlockingCollection实现简易消息队列

    前言 消息队列现今的应用场景越来越大,常用的有RabbmitMQ和KafKa. 我们用BlockingCollection来实现简单的消息队列. 实现消息队列 用Vs2017创建一个控制台应用程序.创 ...

  3. NodeMCU学习(三) : 进入网络世界

    把NodeMCU连接到路由器网络上 NodeMCU可以被配置为Station模式和softAP模式或者Station + AP模式,当它被配置为Station模式时,就可以去连接Access Poin ...

  4. LINUX内核分析第二周学习总结——操作系统是如何工作的

    LINUX内核分析第二周学习总结——操作系统是如何工作的 张忻(原创作品转载请注明出处) <Linux内核分析>MOOC课程http://mooc.study.163.com/course ...

  5. 记初学net-SNMP

    自从弄完那个jsp的网盘(其实还是个烂摊子),这几天一直在研究snmp. 有需求就激发动力,对,人都是被逼出来的.五一这几天,天天搁这坐着,毫无头绪. 下面切入正题. 要做一个监控园区网在线数的平台, ...

  6. 运行Maven时报错:No goals have been specified for this build

    No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in t ...

  7. c++实现计算器功能 -----初代

    由于时间问题,我就写的简单一点. 课程作业一 git链接: Operations 里面的Operations.cpp文件就是完成品. 1 我就简单的对我原来的代码进行了重构,原本的代码已经把函数都分得 ...

  8. Mininet入门与实战 3.9参课记录

    Mininet入门与实战 Mininet简介 由来:斯坦福大学发明,基于Linux Container架构开发的进程虚拟化网络仿真工具,交换机支持OF协议. 使用情况: 控制器,不推荐自带控制器(bu ...

  9. week9:个人博客作业

    团队作业(5) 以下内容多数是网上的内容,只是做了整合的过程. 要求 在PM 带领下, 每个团队深入分析下面行业的App, 找到行业的Top 5 (从下面的三个备选中,任选一个行业即可) 英语学习/词 ...

  10. final发布48小时用户调查报告

    小组名称:飞天小女警 项目名称:礼物挑选小工具 小组成员:沈柏杉(组长).程媛媛.杨钰宁.谭力铭 调查问卷标题:用户调查报告 调查目的:在final版本发布后的用户调查报告 调查问卷的数量:11 问卷 ...