Java.io.OutputStream.write() Method



Description

The java.io.OutputStream.write(byte[] b) method writes b.length bytes from the specified byte array to this output stream. The general contract for write(b) is that it should have exactly the same effect as the call write(b, 0, b.length)

Declaration

Following is the declaration for java.io.OutputStream.write() method.

public void write(byte[] b)

Parameters

b − The data.

Return Value

This method does not return a value.

Exception

IOException − If an I/O error occurs.

Example

The following example shows the usage of java.io.OutputStream.write() method.

package com.tutorialspoint;

import java.io.*;

public class OutputStreamDemo {
   public static void main(String[] args) {
      byte[] b = {'h', 'e', 'l', 'l', 'o'};
      
      try {
         // create a new output stream
         OutputStream os = new FileOutputStream("test.txt");

         // craete a new input stream
         InputStream is = new FileInputStream("test.txt");

         // write something
         os.write(b);

         // read what we wrote
         for (int i = 0; i < b.length; i++) {
            System.out.print("" + (char) is.read());
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

hello
java_io_outputstream.htm
Advertisements