Apache Commons IO组件简介说明

书欣 Java教程 发布时间:2022-08-18 16:10:05 阅读数:11983 1
下文笔者讲述Apache Commons IO组件的功能简介说明,如下所示

Apache Commons IO组件简介

Apache Commons IO 提供一组对IO操作的实用工具类
实现思路:
    1.引入相应的jar包
	2.使用类中相应的方法

Maven依赖

在项目的pom.xml文件中,
引入相应的依赖信息
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

FileUtils类

该类提供对文件的不同操作,如打开、读取、复制和移动。
例:
 
   @Test
    public void test1() throws IOException {
        //获取类路径下文件
        File file = FileUtils.getFile(getClass().getClassLoader()
                .getResource("fileTest.txt")
                .getPath());
        //获取临时文件夹
        File tempDir = FileUtils.getTempDirectory();
        //复制文件到临时文件夹下
        FileUtils.copyFileToDirectory(file, tempDir);
        //获取临时文件夹下文件
        File newTempFile = FileUtils.getFile(tempDir, file.getName());
        String data = FileUtils.readFileToString(newTempFile,
                Charset.defaultCharset());
        System.out.println(data);
    }

FilenameUtils

此实用程序提供了一种与操作系统无关的方式来对文件名执行常见功能。
 
   @Test
    public  void test2(){
        String path="D:\\test.txt";
        //从完整文件名中获取完整路径,即前缀 + 路径。
        String fullPath = FilenameUtils.getFullPath(path);
        System.out.println("fullPath:"+fullPath);
        //获取文件后缀
        String extension = FilenameUtils.getExtension(path);
        System.out.println("extension:"+extension);
        //获取文件名 不包含后退
        String baseName = FilenameUtils.getBaseName(path);
        System.out.println("baseName:"+baseName);
    }
 

FileSystemUtils

 
 FileSystemUtils可检查给定卷或驱动器上的可用空间

输入和输出

TeeInputStream 和 TeeOutputSteam
例:
  
    @Test
    public void test4() throws IOException {
        String str = "Hello World.";
        ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
        ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
        ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();

        FilterOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);

        new TeeInputStream(inputStream, teeOutputStream, true).read(new byte[str.length()]);

        System.out.println(outputStream1);//Hello World.
        System.out.println(outputStream2);//Hello World.
    }
 

Filters

Commons IO 包括一个有用的文件过滤器列表
当想要从异构文件列表中缩小到特定的所需文件列表时
该库还支持对给定文件列表的 AND 和 OR 逻辑运算
例:
 
   @Test
    public void test5() {

        String path = getClass().getClassLoader()
                .getResource("fileTest.txt")
                .getPath();
        //获取文件夹
        File dir = FileUtils.getFile(FilenameUtils.getFullPath(path));


        String[] txts = dir.list(new AndFileFilter(
                new WildcardFileFilter("*ple*", IOCase.INSENSITIVE),
                new SuffixFileFilter("txt")));
        assert txts != null;
        String collect = String.join(",", txts);
        System.out.println(collect);

    }
 

Comparators

Comparator 包提供了不同类型的文件比较。
PathFileComparator
PathFileComparator 类可用于按文件的路径以区分大小写、不区分大小写
或依赖于系统的区分大小写的方式对文件列表或数组进行排序
 
  @Test
    public void test6() {

        PathFileComparator pathFileComparator = new PathFileComparator(
                IOCase.INSENSITIVE);
        String path = FilenameUtils.getFullPath(getClass()
                .getClassLoader()
                .getResource("fileTest.txt")
                .getPath());
        File dir = new File(path);
        File[] files = dir.listFiles();

        pathFileComparator.sort(files);
        for (File file : files) {
            System.out.println(file.getName());
        }

    } 
 

SizeFileComparator

SizeFileComparator 用于比较两个文件的大小(长度)
当第一个文件的大小小于第二个文件的大小
则返回一个负整数值
当文件大小相等,则返回零
当第一个文件的大小大于第二个文件的大小,则返回正值
例:
 
    @Test
    public void test7() {

        SizeFileComparator sizeFileComparator = new SizeFileComparator();
        File largerFile = FileUtils.getFile(getClass().getClassLoader()
                .getResource("fileTest.txt")
                .getPath());
        File smallerFile = FileUtils.getFile(getClass().getClassLoader()
                .getResource("sample.txt")
                .getPath());

        int i = sizeFileComparator.compare(largerFile, smallerFile);
        System.out.println(i);
    }
 

文件监视器

Commons IO 监视器包提供跟踪文件或目录更改的功能
当 FileAlterationMonitor启动时
将开始接收有关正在监视的目录上的文件更改的通知:
 
public class FileMonitor {
    public static void main(String[] args) throws Exception {
        //File folder = FileUtils.getTempDirectory();
        File folder = new File("D:\\");
        startFileMonitor(folder);
    }

    public static void startFileMonitor(File folder) throws Exception {
        FileAlterationObserver observer = new FileAlterationObserver(folder);
        FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
         //FileAlterationListenerAdaptor 提供了很多方法
        FileAlterationListener fal = new FileAlterationListenerAdaptor() {

            @Override
            public void onFileCreate(File file) {
                // on create action
                System.out.println("create file name:" + file.getName());
            }

            @Override
            public void onFileDelete(File file) {
                // on delete action
                System.out.println("delete file name:" + file.getName());
            }
        };

        observer.addListener(fal);
        monitor.addObserver(observer);
        monitor.start();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaCourse/202208/4249.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者