Using InputStream in Java

InputStream is the abstract super class for all input streams. It declares the three basic methods needed to read bytes of data from a stream. It also has methods for closing streams,checking how many bytes of data are available to be read,skipping over input,marking a position in a stream and resetting back to that position,and determining whether marking and resetting are supported.

Reading data

The fundamental method of the InputStream class is read(). This method reads a single unsigned byte of data and returns the integer value of the unsigned byte. This is a number between 0 and 255:

public abstract int read() throws IOException

read() is declared abstract;therefore,InputStream is abstract. You can never instantiate an InputStream directly;you always work with one of its concrete subclasses.
Example:

  try{while (true){ int datum = System.in.read(); if (datum == -1) break; System.out.println(datum);}  } catch (IOException ex){System.err.println("Couldn't read from System.in!"); }

Reading arrays of bytes

Input and output are often the performance bottlenecks in a program. Reading from or writing to disk can be hundreds of times slower than reading from or writing to memory;network connections and user input are even slower. While disk capacities and speeds have increased over time,they have never kept pace with CPU speeds.
All input streams have overloaded read() methods that read chunks of contiguous data into a byte array. The first variant tries to read enough data to fill the array. The second variant tries to read length bytes of data starting at position offset into the array. Neither of these methods is guaranteed to read as many bytes as you want. Both methods return the number of bytes actually read,or -1 on end of stream.

public int read(byte[] data) throws IOExceptionpublic int read(byte[] data,int offset,int length) throws IOException

The default implementation of these methods in the InputStream class merely calls the basic read() method enough times to fill the requested array or subarray. However,most subclasses of InputStream override these methods with more efficient methods,perhaps native,that read the data from the underlying source as a block.

try{byte[] buffer = new byte[1024]; while (true){int bytesRead = in.read(buffer);if (bytesRead == -1) break;out.write(buffer,0,bytesRead)} catch (IOException ex){System.err.println("Couldn't read from System.in!")}

Counting the Available Bytes

It’s sometimes convenient to know how many bytes can be read before you attempt to read them. The InputStream class’s available() method tells you how many bytes you can read without blocking. It returns 0 if there’s no data available to be read.

public int available() throws IOException

For example:

try{byte[] b = new byte[System.in.available()];System.in.read(b)}catch (IOException ex){System.err.println("Couldn't read from System.in!")}

Correct closing Input Streams

As with output streams,input streams should be closed when you’re through with them to release any native resources such as file handles or network ports that the stream is holding onto. To close a stream,call its close() method:

public void close() throws IOException

Once you have closed an input stream,you should no longer read from it. Most attempts to do so will throw an IOException (there are a few exceptions).

// Initialize this to null to keep the compiler from complaining// about uninitialized variablesInputStream in = null;try{URL u = new URL("http://thedevelopersinfo.com/");in = u.openStream();// Read from the stream...}finally{if (in != null) in.close()}

Extending InputStream

Immediate subclasses of InputStream must provide an implementation of the abstract read() method. They may also override some of the non abstract methods. For example,the default markSupported() method returns false,mark() does nothing,and reset() throws an IOException. Any class that allows marking and resetting must override these three methods. Subclasses should also override available() to return something other than 0. Furthermore,they may override skip() and the other two read() methods to provide more efficient implementations.
Example:

import java.io.IOException;import java.io.InputStream;import java.util.Random;public class RandomInputStream extends InputStream{ private Random generator = new Random(); private boolean closed = false; public int read() throws IOException{ checkOpen(); int result = generator.nextInt() % 256; if (result < 0){ result = -result; }  return result; }  public int read(byte[] data,int offset,int length) throws IOException{ checkOpen(); byte[] temp = new byte[length]; generator.nextBytes(temp); System.arraycopy(temp,0,data,offset,length); return length; }  public int read(byte[] data) throws IOException{ checkOpen(); generator.nextBytes(data); return data.length; }  public long skip(long bytesToSkip) throws IOException{ checkOpen(); // It's all random so skipping has no effect.  return bytesToSkip; }  public void close(){ this.closed = true; }  private void checkOpen() throws IOException{ if (closed){ throw new IOException("Input stream closed"); }  }  public int available(){ // Limited only by available memory and the size of an array.  return Integer.MAX_VALUE; }}

That's all.

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.