Home  >  Core Java

Java OutputStreamWriter and InputStreamReader Example

By Arvind Rai, July 19, 2014
In this page we will learn java.io.OutputStreamWriter and java.io. InputStreamReader. These APIs has been introduced in JDK 1.1.

OutputStreamWriter

OutputStreamWriter behaves as a bridge to transfer data from character stream to byte stream. It uses default charset or we can specify charset for change in character stream to byte stream.
OutputStreamWriterDemo.java
package com.cp.io;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamWriterDemo {
	public static void main(String[] args) {
        String str = "Hello World! \nThis is OutputStreamWriter Code Example.";
        BufferedWriter bw = null;
        try {
          Writer w = new OutputStreamWriter(System.out);  
          bw = new BufferedWriter(w);
          bw.write(str);
        } catch (IOException e) {
           e.printStackTrace();
        }finally {
            try {
                bw.close();
              } catch (IOException ex) {
                ex.printStackTrace();
              }
         }
    }
} 
Output
Hello World! 
This is OutputStreamWriter Code Example.

InputStreamReader

InputStreamReader behaves as bridge from bytes stream to character stream. It also uses charset to decode byte stream into character stream.
InputStreamReaderDemo.java
package com.cp.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamReaderDemo {
	public static void main(String[] args) {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		int a=0;
		int b=0;
		try {
			System.out.println("Enter a number..");
			a = Integer.parseInt(br.readLine());
			System.out.println("Enter another number..");
		    b = Integer.parseInt(br.readLine());
		    
		} catch (NumberFormatException e) {
				e.printStackTrace();
		} catch (IOException e) {
				e.printStackTrace();
		}	
		System.out.println("you enterd "+a+" and  "+b);
	}
} 
Output
Enter a number..
10
Enter another number..
14
you enterd 10 and  14
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us