InputStream Reader and Writer


InputStream Reader

This class is a bridge from byte streams to character streams. It is used for reading bytes and decoding into characters using a specified charset.

Syntax for java.io.InputStreamReader class:

public class InputStreamReader extends Reader

Example :

public class InputStreamReaderExample { public static void main(String[] args) { try { InputStream stream = new FileInputStream("knowledge2life.txt"); Reader reader = new InputStreamReader(stream); int data = reader.read(); while (data != -1) { System.out.print((char) data); data = reader.read(); } } catch (Exception e) { e.printStackTrace(); } } }

OUTPUT:

Welcome to Knowledge2life.

OutputStream Writer

This class is a bridge from character streams to byte streams. It is used for encoding the characters into bytes using a specified charset.

Syntax for java.io.OutputStreamWriter class:

public class OutputStreamWriter extends Writer

Example :

public class OutputStreamWriterExample { public static void main(String[] args) { try { OutputStream outputStream = new FileOutputStream("output.txt"); Writer outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write("Hello Knowledge2life"); outputStreamWriter.close(); } catch (Exception e) { e.getMessage(); } } }

OUTPUT:

output.txt file will contains text "Hello Knowledge2life "