在前面的 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
运行时异常.