Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

OSGL (Part 4): The Art of IO Operations

DZone's Guide to

OSGL (Part 4): The Art of IO Operations

As we continue this series on OSGL, see how you can make use of its IO library to help making coding simple, though with a caveat for exceptions.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

In the previous OSGL art of coding articles, we have talked about:

In this article, we will introduce how to use the IO utility to handle Input/Output operations.

Again let's show the code.

First, we will prepare some variables and content:

@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();
    }
}

The following testing code reviews the use of Fluent coding API of the IO utility:

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);
    }
}

Note: One major thing about the IO utility is it eclipses the checked IOException with the unchecked UnexpectedIOException in all methods. So there is no need to add throws IOException to your method that use OSGL IO to deal with IO operations.

More About Checked vs. Unchecked Exceptions

There are two groups of Java developers: one argues for checked exceptions while the other side argues against them. I am in the second group, and I prefer to eliminate checked exceptions and make APIs more programmer friendly. For people who do not accept this, then the OSGL IO library might not be your tool. For more information about checked exceptions vs. unchecked exceptions, this might be a good reference.

Below is the demonstration of other IO utility methods:

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(newbyte[]{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, ...);


Summary

We have demonstrated the following two aspects of the OSGL IO library:

  1. The Fluent API design makes the IO operation coding much more expressive.
  2. The checked IOExcpetion has been wrapped with non-checked UnexpectedIOException make IO coding simple and concise.

To use the OSGL library, add the following dependencies to your pom.xml file:

<dependency>
    <groupId>org.osgl</groupId>
    <artifactId>osgl-tool</artifactId>
    <version>${osgl-tool.version}</version>
</dependency>


At the moment the osgl-tool.version is 1.10.0.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,io ,fluent api ,osgl ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}