Using Sequence Input Stream in Java

In this post I am going to show you how to use SequenceInputStream in Java. A SequenceInputStream first reads all the bytes from the first stream in the sequence,then all the bytes from the second,third and so on. When the end of one stream is reached,that stream is closed and the next data comes from the next stream.
In this example I will read content from 2 websites:

import java.io.IOException;import java.io.InputStream;import java.io.SequenceInputStream;import java.net.MalformedURLException;import java.net.URL;public class Main{ public static void main(String[] args) throws MalformedURLException,IOException{ URL home_url = new URL("http://thedevelopersinfo.com"); URL old_url = new URL("http://thedevelopersinfo.wordpress.com"); InputStream inputStream = new SequenceInputStream(home_url.openStream(),old_url.openStream()); for(int i = inputStream.read();i != -1;i = inputStream.read()){ System.out.write(i); }  }}

As you can see it is very simple. I found this class very useful in cases when I need to read data from several streams in some order. For example in my current project I read data from several log files and create new one with selected data.

Download code from this post.

If you’d like to get the latest posts as soon as they’re published,subscribe to website’s feed!

Share

No related posts.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.