设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客
LUPA开源社区 首页 业界资讯 技术文摘 查看内容

Apache Commons IO入门教程

2014-11-13 11:41| 发布者: joejoe0332| 查看: 2662| 评论: 0|原作者: importnew.com|来自: importnew.com

摘要: Apache Commons IO是Apache基金会创建并维护的Java函数库。它提供了许多类使得开发者的常见任务变得简单,同时减少重复(boiler-plate)代码,这些代码可能遍布于每个独立的项目中,你却不得不重复的编写。这些类由 ...


1.4 比较器

使用org.apache.commons.io.comparator 包下的类可以让你轻松的对文件或目录进行比较或者排序。你只需提供一个文件列表,选择不同的类就可以实现不同方式的文件比较。

ComparatorExample.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
73
74
75
import java.io.File;
import java.util.Date;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.comparator.SizeFileComparator;
 
public final class ComparatorExample {
 
    private static final String PARENT_DIR =
            "C:UsersLilykosworkspaceApacheCommonsExampleExampleFolder";
 
    private static final String FILE_1 =
            "C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexample";
 
    private static final String FILE_2 =
            "C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleTxt.txt";
 
    public static void runExample() {
        System.out.println("Comparator example...");
 
        //NameFileComparator
 
        // Let's get a directory as a File object
        // and sort all its files.
        File parentDir = FileUtils.getFile(PARENT_DIR);
        NameFileComparator comparator = new NameFileComparator(IOCase.SENSITIVE);
        File[] sortedFiles = comparator.sort(parentDir.listFiles());
 
        System.out.println("Sorted by name files in parent directory: ");
        for (File file: sortedFiles) {
            System.out.println("t"+ file.getAbsolutePath());
        }
 
        // SizeFileComparator
 
        // We can compare files based on their size.
        // The boolean in the constructor is about the directories.
        //      true: directory's contents count to the size.
        //      false: directory is considered zero size.
        SizeFileComparator sizeComparator = new SizeFileComparator(true);
        File[] sizeFiles = sizeComparator.sort(parentDir.listFiles());
 
        System.out.println("Sorted by size files in parent directory: ");
        for (File file: sizeFiles) {
            System.out.println("t"+ file.getName() + " with size (kb): " + file.length());
        }
 
        // LastModifiedFileComparator
 
        // We can use this class to find which file was more recently modified.
        LastModifiedFileComparator lastModified = new LastModifiedFileComparator();
        File[] lastModifiedFiles = lastModified.sort(parentDir.listFiles());
 
        System.out.println("Sorted by last modified files in parent directory: ");
        for (File file: lastModifiedFiles) {
            Date modified = new Date(file.lastModified());
            System.out.println("t"+ file.getName() + " last modified on: " + modified);
        }
 
        // Or, we can also compare 2 specific files and find which one was last modified.
        //      returns > 0 if the first file was last modified.
        //      returns  0)
            System.out.println("File " + file1.getName() + " was modified last because...");
        else
            System.out.println("File " + file2.getName() + "was modified last because...");
 
        System.out.println("t"+ file1.getName() + " last modified on: " +
                new Date(file1.lastModified()));
        System.out.println("t"+ file2.getName() + " last modified on: " +
                new Date(file2.lastModified()));
    }
}
输出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Comparator example...
Sorted by name files in parent directory:
    C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldercomparator1.txt
    C:UsersLilykosworkspaceApacheCommonsExampleExampleFoldercomperator2.txt
    C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexample
    C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleFileEntry.txt
    C:UsersLilykosworkspaceApacheCommonsExampleExampleFolderexampleTxt.txt
Sorted by size files in parent directory:
    example with size (kb): 0
    exampleTxt.txt with size (kb): 87
    exampleFileEntry.txt with size (kb): 503
    comperator2.txt with size (kb): 1458
    comparator1.txt with size (kb): 4436
Sorted by last modified files in parent directory:
    exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014
    example last modified on: Sun Oct 26 23:42:55 EET 2014
    comparator1.txt last modified on: Tue Oct 28 14:48:28 EET 2014
    comperator2.txt last modified on: Tue Oct 28 14:48:52 EET 2014
    exampleFileEntry.txt last modified on: Tue Oct 28 14:53:50 EET 2014
File example was modified last because...
    example last modified on: Sun Oct 26 23:42:55 EET 2014
    exampleTxt.txt last modified on: Sun Oct 26 14:02:22 EET 2014

让我们来看看这里用到了哪些类:

NameFileComparator:通过文件名来比较文件。

SizeFileComparator:通过文件大小来比较文件。

LastModifiedFileComparator:通过文件的最新修改时间来比较文件。

在这里你需要注意,比较可以在定的文件夹中(文件夹下的文件已经被sort()方法排序过了),也可以在两个指定的文件之间(通过使用compare()方法)。

1.5 输入

在org.apache.commons.io.input包下有许多InputStrem类的实现,我们来测试一个最实用的类,TeeInputStream,将InputStream以及OutputStream作为参数传入其中,自动实现将输入流的数据读取到输出流中。而且,通过传入第三个参数,一个boolean类型参数,可以在数据读取完毕之后自动关闭输入流和输出流。

InputExample.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
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.input.XmlStreamReader;
 
public final class InputExample {
 
    private static final String XML_PATH =
            "C:UsersLilykosworkspaceApacheCommonsExampleInputOutputExampleFolderweb.xml";
 
    private static final String INPUT = "This should go to the output.";
 
    public static void runExample() {
        System.out.println("Input example...");
        XmlStreamReader xmlReader = null;
        TeeInputStream tee = null;
 
        try {
 
            // XmlStreamReader
 
            // We can read an xml file and get its encoding.
            File xml = FileUtils.getFile(XML_PATH);
 
            xmlReader = new XmlStreamReader(xml);
            System.out.println("XML encoding: " + xmlReader.getEncoding());
 
            // TeeInputStream
 
            // This very useful class copies an input stream to an output stream
            // and closes both using only one close() method (by defining the 3rd
            // constructor parameter as true).
            ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
 
            tee = new TeeInputStream(in, out, true);
            tee.read(new byte[INPUT.length()]);
 
            System.out.println("Output stream: " + out.toString());        
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try { xmlReader.close(); }
            catch (IOException e) { e.printStackTrace(); }
 
            try { tee.close(); }
            catch (IOException e) { e.printStackTrace(); }
        }
    }
}
输出
Input example...
XML encoding: UTF-8
Output stream: This should go to the output.

1.6 输出

与org.apache.commons.io.input包中的类相似, org.apache.commons.io.output包中同样有OutputStream类的实现,他们可以在多种情况下使用,一个非常有意思的类就是 TeeOutputStream,它可以将输出流进行分流,换句话说我们可以用一个输入流将数据分别读入到两个不同的输出流。

OutputExample.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
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
 
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;
 
public final class OutputExample {
 
    private static final String INPUT = "This should go to the output.";
 
    public static void runExample() {
        System.out.println("Output example...");
        TeeInputStream teeIn = null;
        TeeOutputStream teeOut = null;
 
        try {
 
            // TeeOutputStream
 
            ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));
            ByteArrayOutputStream out1 = new ByteArrayOutputStream();
            ByteArrayOutputStream out2 = new ByteArrayOutputStream();
 
            teeOut = new TeeOutputStream(out1, out2);
            teeIn = new TeeInputStream(in, teeOut, true);
            teeIn.read(new byte[INPUT.length()]);
 
            System.out.println("Output stream 1: " + out1.toString());
            System.out.println("Output stream 2: " + out2.toString());
 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // No need to close teeOut. When teeIn closes, it will also close its
            // Output stream (which is teeOut), which will in turn close the 2
            // branches (out1, out2).
            try { teeIn.close(); }
            catch (IOException e) { e.printStackTrace(); }
        }
    }
}
输出
1
2
3
Output example...
Output stream 1: This should go to the output.
Output stream 2: This should go to the output.

2. 下载完整的示例

这是一个Apache Commons IO的入门指导,为开发者介绍了一些可以为你提供轻松解决方案的类。在这个庞大的函数库里面还有包含很多其他的功能,相信这些例子可以在你未来的项目开发中成为你非常有用工具!

 

 
原文链接: Apache Commons IO入门教程 翻译: ImportNew.com - yewenhai
译文链接: http://www.importnew.com/13715.html

酷毙

雷人

鲜花

鸡蛋

漂亮
  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部