OSGL 工具库 - IO 操作的艺术

在前面的 OSGL 工具库之编程艺术系列中我们讲述了

本文中我们将介绍如何使用 OSGL IO 工具类来处理输入输出操作.

依旧是老规矩: 用代码来写博客

首先准备测试变量:

@Ignore
public static class Base extends TestBase {

    protected static String content;
    protected static C.List<String> lines;
    protected static int lineNumber;

    @Before
    public void prepareContent() {
        lineNumber = 5 + N.randInt(10);
        lines = C.newList();
        for (int i = 0; i < lineNumber; ++i) {
            lines.add(S.random());
        }
        content = S.join(lines).by("\n").get();
    }
}

下面的测试代码可以看出如何使用 IO 库进行操作:

public static class FluentIOTest extends Base {
    @Test
    public void testReadStringIntoLines() {
        eq(lines, IO.read(content).toLines());
    }

    @Test
    public void testWriteStringIntoOutputStream() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IO.write(content).to(baos);
        eq(content, new String(baos.toByteArray()));
    }

    @Test
    public void testWriteByteArrayIntoOutputStream() {
        byte[] ba = {1, 2, 3};
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IO.write(ba).to(baos);
        eq(ba, baos.toByteArray());
    }

    @Test
    public void testWriteByteArrayIntoFile() throws IOException  {
        File file = File.createTempFile("osgl", ".tmp");
        byte[] ba = {1, 2, 3};
        IO.write(ba).to(file);
        byte[] ba0 = IO.read(file).toByteArray();
        eq(ba, ba0);
    }
}

其他 IO 工具演示:

Flushable f;
IO.flush(f);

Closable c;
IO.close(c);

InputStream is;
is = IO.inputStream(); // an empty inputstream
is = IO.inputStream("ABC"); // an input stream of string "ABC"
is = IO.inputStream(new byte[]{1, 2, 3}); 
is = IO.inputStream(new File("/etc/bash.bashrc"));
is = IO.inputStream(MyClass.getResource("/app.properties"));

Reader r;
r = IO.reader(); // an empty reader
r = IO.reader("ABC");
r = IO.reader("ABC".getBytes()):
r = IO.reader(new File("/etc/bash.bashrc"));
r = IO.reader(MyClas.getResource("/app.properties"));

File tmpDir = new File("/tmp");
File tmpFoo = IO.child(tmpDir, "foo.txt"); // /tmp/foo.txt
File tmpDir2 = IO.parent(tmpFoo);
List<File> files = IO.children(tmpDir);

String s0 = IO.checksum(new File("/etc/bash.bashrc"));
String s1 = IO.checksum(IO.inputStream(new File("/etc/bash.bashrc"));

BufferedInputStream is0 = IO.buffered(myOtherInputStream);
BufferedOutputStream os0 = IO.buffered(myOtherOutputStream);
BufferedReader r0 = IO.buffered(myOtherReader);
BufferedWriter w0 = IO.buffered(myOtherWriter);

File tmpZip = IO.zip(f0, f1, ...);
File givenZipFile = ...
IO.zipInto(givenZipFile, f0, f1, ...);

特别提示, OSGL IO 库所有的操作都不会抛出 IOException 异常, 如果有 IO 异常, OSGL IO 库会抛出 UnexpectedIOException 运行时异常.

转载于:https://my.oschina.net/greenlaw110/blog/1790370

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值