BufferedInputStream

Java BufferedInputStream Example

In this example we will discuss about BufferedInputStream class and its usage. The BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.

BufferedInputStream extends FilterInputStream, which simply overrides all methods of InputStream with versions that pass all requests to the contained input stream.

The BufferedInputStream class exists since JDK1.0.

The structure of BufferedInputStream

Constructor:

  • BufferedInputStream(InputStream in)Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
  • BufferedInputStream(InputStream in, int size)Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.

The BufferedInputStream in Java

To see a basic usage of the BufferedInputStream, create a class called SimpleBufferedInputStreamExample with the following source code:

package com.javacodegeeks.examples;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class SimpleBufferedInputStreamExample {

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:/file.txt"));
			
			while(in.available()>0) {
				sb.append((char) in.read());
			}
			
			System.out.println("read this:");
			System.out.println(sb.toString());
			in.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}

}

I used the BufferedInputStream to read from a file and show the output of it in the console. Firstly, I created a BufferedInputStream instance from a FileInputStream. Then, I appended every char into a StringBuilder, to finally print it as a string.

In the end, don’t forget to close the BufferedInputStream instance.

The output of this program is:

read this:
This is the first line of the file
This is the second line of the file

This was the content of the file I read.

A better usage of BufferedInputStream

Just like in the above example, the BufferedInputStream can be used to get a response from a web service. To show how to do this, create a class called HttpClient in a webclient package:

package com.javacodegeeks.examples.webclient;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpClient {
	
	private URL baseUrl;
	
	public HttpClient(String baseUrl) throws MalformedURLException {
		this.baseUrl = new URL(baseUrl);
	}
	
	public HttpClient(URL u) {
		this.baseUrl = u;
	}
	
	public String get(String route) throws IOException {
		StringBuilder sb = new StringBuilder();
		String base = this.baseUrl.getHost();
		URL u = new URL("http://"+base + route);
		URLConnection conn = u.openConnection();
		
		BufferedInputStream input = new BufferedInputStream(conn.getInputStream());
		
		while (input.available()>0) {
			  sb.append((char) input.read());
		}
		
		return sb.toString();
	}
}

This class creates a HTTP client. I only implemented the GET method, but the other methods implementation is similar. The get() method returns the response of the HTTP service into a string, and you can then parse this string with any method you would like.

To use this class, create a Main class and put this code into it:

package com.javacodegeeks.examples.webclient;

import java.io.IOException;
import java.net.MalformedURLException;

public class Main {

	public static void main(String[] args) {

		try {
			HttpClient client = new HttpClient("http://httpbin.org");
			
			String myIp = client.get("/ip");
			System.out.println(myIp);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

I used a simple HTTP service, http://httpbin.org/, to test my HttpClient class.

When I send a GET request to get my IP address, it returns a JSON with the useful information. Then, you can use a JSON parser, like this one, to interpret the result.

My output here is:

{
  "origin": "79.106.109.165"
}

More about the BufferedInputStream in Java

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

Download Code

Download
You can download the full source code of this example here : BufferedInputStreamExample

Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button