Using OutputStream in Java

OutputStream class declares basic methods which you need to write bytes of data onto a stream.

Writing bytes to the OutputStream

OutputStream class has write() method which is fundamental:

public abstract void write(int b) throws IOException

This method writes a byte of data whose value should be between 0 and 255. If I pass a number larger than 255 or smaller than 0,it’s reduced modulo 256 before being written. Here I want to show simple example which shows how to write bytes to the Output Stream through write() method:

public class Main{ public static void main(String[] args){ for (int i = 32;i < 127;i++){ System.out.write(i); if (i % 4 == 3){System.out.write('\n'); } else{System.out.write('\t'); }  }  System.out.write('\n'); }}

That's all.

 

Download this example.

Writing arrays of bytes to the OutputStream

Writing arrays of bytes is much faster than write data byte to byte.
Java has for this 2 methods:

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

I did some research and found that files are often best written in small multiples of the block size of the disk,typically 1024,2048,or 4096 bytes,network connections often require smaller buffer sizes 128 or 256 bytes. The optimal buffer size depends on too many system-specific details for anything to be guaranteed,but I recommend to use 128 bytes for network connections and 1024 bytes for files.
Example:

import java.io.IOException;public class Main{ public static void main(String[] args){ byte[] b = new byte[(127 - 31) * 2]; int index = 0; for (int i = 32;i < 127;i++){ b[index++] = (byte) i; if (i % 4 == 3){b[index++] = (byte) '\n'; } else{b[index++] = (byte) '\t'; }  }  b[index++] = (byte) '\n'; try{ System.out.write(b); } catch (IOException ex){ System.err.println(ex); }  }}

That's all.

 

Download this example.

Correct closing the OutputStreams

When you're working with a stream,you should close it after all operations. This allows the operating system to free any resources associated with the stream.
To close a stream use

public void close( ) throws IOException

Let's look at correct way for closing an output stream

// Initialize this to null to keep the compiler from complaining// about uninitialized variablesOutputStream out == null;try{out = new FileOutputStream("someFile");// write to the stream...}finally{if (out != null) out.close( )}

Look at finally block. It's best practice. Always close your output stream in finally block.

Extending the OutputStream

OutputStream is an abstract class that describes the operations available with any OutputStream object. Specific subclasses know how to write bytes to particular destinations. There are three overloaded variants of the write() method in OutputStream,one abstract,two concrete:

public abstract void write(int b) throws IOExceptionpublic void write(byte[] data) throws IOExceptionpublic void write(byte[] data,int offset,int length) throws IOException

Subclass must implement the abstract write(int b) method. Also override the third variant write(byte[],data int offset,int length),to improve performance.
Easy variant:

public void write(byte[] data,int offset,int length) throws IOException{for (int i = offset;i < offset+length;i++) write(data[i])}

Example which I am going to show is simple. It extends OutputStream,overrides write() method. Also I am going to put System.out for showing result:

import java.io.IOException;import java.io.OutputStream;public class NewOutputStream extends OutputStream{ private boolean closed = false; @Override  public void write(int b) throws IOException{ if (closed){ throw new IOException("Write to closed stream"); }  char c = (char) b; System.out.println(String.valueOf(c)); }  @Override  public void close(){ closed = true; }}

and main class

import java.io.IOException;import java.io.OutputStream;public class Main{ public static void main(String[] args) throws IOException{ OutputStream out = new NewOutputStream(); out.write(35); }}

That's all. It works.
Don't forget that for extending you have to override write(int b) method.

 

Download this example.

 

Want to have latest information from this site? Subscribe to our 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.