Guava: Some useful IO utilities

Guava IO package provides very useful utility classes for input/ouput stream, byte stream, file handling and many more.

Here are few example which show case how these utilities can make your code much cleaner, modular and more readable.

 

Copy “InputStream” to “OutputStream

 

        InputStream is = CopyStreams.class.getResourceAsStream("test.txt");
        OutputStream os = System.out;
        ByteStreams.copy(is, os);

 

Changing InputStream to “byte[]”

 

        InputStream is = CopyStreams.class.getResourceAsStream("test.txt");

        byte[] isBytes = ByteStreams.toByteArray(is);      

 // Now if you want to get base64 encoded string then it will be like this  
        String isBase64Str = new sun.misc.BASE64Encoder().encode(isBytes);

 

Combining two files in one

 

        File input1 = new File("c:\\testio\\AWords.txt");
        File input2 = new File("c:\\testio\\BWords.txt");
        File output = new File("c:\\testio\\ABWords.txt");
        
        InputSupplier<InputStreamReader> rs1 = Files.newReaderSupplier(input1, Charsets.UTF_8);
        InputSupplier<InputStreamReader> rs2 = Files.newReaderSupplier(input2, Charsets.UTF_8);        
        InputSupplier<Reader> combined = CharStreams.join(rs1, rs2);
        
        OutputSupplier<OutputStreamWriter> ws = Files.newWriterSupplier(output, Charsets.UTF_8, false);
        CharStreams.copy(combined, ws);

 

Processing the file

 

public class IOTest {
    public static LineProcessor<List<String>> collectWordsStartWithZ = 
        new LineProcessor<List<String>>() {
            List<String> collector = Lists.newArrayList();
            final static String PREFIX = "z";
    
            @Override
            public boolean processLine(String line) {
                String line_ = Strings.nullToEmpty(line).trim().toLowerCase();
                if (!line_.isEmpty() && line_.startsWith(PREFIX)) {
                    collector.add(line);
                }
                return true;
            }
    
            @Override
            public List<String> getResult() {
                return collector;
            }
        };

    public static void main(String[] args) throws IOException {
        URL resource = IOTest.class.getResource("test.txt");
        List<String> lines = Resources.readLines(resource, Charsets.UTF_8, collectWordsStartWithZ);

        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Comments

Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Application Design Notes

How to store user password at server!!!