Character Streams in Java

Character Streams in Java with Examples

In this article, I am going to discuss Character Streams in Java with Examples. Please read our previous article where we discussed Java Byte Streams in detail. As part of this article, you will understand the need and use of the following classes related to Java Character Streams.

  1. PrintWriter Class in Java
  2. InputStreamReader Class
  3. OutputStreamWriter class in java
  4. FileReader Class in Java
  5. FileWriter class in Java
  6. BufferedReader class in Java
  7. BufferedWriter Class in Java
  8. StringReader Class in Java
  9. StringWriter Class in Java

Note: The Stream which read and writes the data in the form of the character is called a character stream. 

PrintWriter Class in Java

Java PrintWriter class is the implementation of the Writer class. It is used to print the formatted representation of objects to the text-output stream. Unlike other writers, PrintWriter converts the primitive data (int, float, char, etc.) into the text format. It then writes that formatted data to the writer. Also, the PrintWriter class does not throw any input/output exceptions. Instead, we need to use the checkError() method to find any error in it.

Creating PrintWriter Object in Java

We can use the following ways to create PrintWriter Class:

Using other Writers
FileWriter file = new FileWriter(“output.txt”);
PrintWriter output = new PrintWriter(file, autoFlush);

Using other output streams
FileOutputStream file = new FileOutputstream(“output.txt”);
PrintWriter output = new PrintWriter(file, autoFlush);

Using filename
PrintWriter output = new PrintWriter(String file, boolean autoFlush);

Example: Program to understand PrintWriter class in java:
import java.io.*;
public class PrintWriterDemo 
{
    public static void main(String args[]) throws Exception
    {    
        String data = "This is a line of text inside the file.";
  try {
   PrintWriter output = new PrintWriter("output.txt");
   output.print(data);
   output.close();
   System.out.println("Success?");
  } catch (Exception e) {
   e.getStackTrace();
  }    
    }
}

Output: Success?
output.txt
This is a line of text inside the file.

Methods of PrintWriter Class in Java
  1. void print(): Prints the specified data to the Writer.
  2. void println(): Prints the data to the Writer along with a new line character at the end.
  3. void printf(): The printf() method can be used to print the formatted string. It includes 2 parameters: formatted string and arguments.
InputStreamReader Class in Java

The InputStreamReader class of the java.io package can be used to convert data in bytes into data in characters. It extends the abstract class Reader. An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or maybe given explicitly, or the platform’s default charset may be accepted.

Creating InputStreamReader: InputStreamReader input = new InputStreamReader (file, Charset cs);

Example: Program to understand InputStreamReader Class in Java
import java.io.*;
public class ISRDemo
{
    public static void main(String[] args) {  
        try  {  
            InputStream stream = new FileInputStream("file.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();  
        }  
    }  
}
Method of InputStreamReader Class in Java
  1. read(): reads a single character from the reader
  2. read(char[] array): reads the characters from the reader and stores them in the specified array
  3. read(char[] array, int start, int length): reads the number of characters equal to length from the reader and stores in the specified array starting from the start.
  4. getEncoding(): It can be used to get the type of encoding that is used to store data in the input stream.
  5. close() : To close the input stream reader, we can use the close() method. Once the close() method is called, we cannot use the reader to read the data.
  6. ready(): checks if the stream is ready to be read
  7. reset(): returns the control to the point in the stream where the mark was set
OutputStreamWriter class in java

The OutputStreamWriter class of the java.io package can be used to convert data in character form into data in bytes form. It extends the abstract class Writer. The OutputStreamWriter class works with other output streams. It is also known as a bridge between byte streams and character streams. This is because the OutputStreamWriter converts its characters into bytes.

Creating OutputStreamWriter: OutputStreamReader output = new OutputStreamReader (file, Charset cs);

Example: Program to understand OutputStreamWriter Class
import java.io.*;
public class OSWDemo 
{
    public static void main(String[] args) {
  try {
   OutputStream outputStream = new FileOutputStream("output.txt");
   Writer outputStreamWriter = new OutputStreamWriter(outputStream);

   outputStreamWriter.write("Hello World");

   outputStreamWriter.close();
   System.out.println("Success");
  } catch (Exception e) {
   e.getMessage();
  }
 }  
}

Output: Success
output.txt
Hello World

Methods of OutputStreamWriter Class in Java
  1. write(): writes a single character to the writer
  2. write(char[] array): writes the characters from the specified array to the writer
  3. write(String data): writes the specified string to the writer
  4. getEncoding(): It can be used to get the type of encoding that is used to write data to the output stream.
  5. close() : To close the output stream writer, we can use the close() method. Once the close() method is called, we cannot use the writer to write the data.
  6. flush(): forces to write all the data present in the writer to the corresponding destination
  7. append(): inserts the specified character to the current writer
FileReader Class in Java

Java FileReader class is used to read data from the file. This is a character stream class that is used to read the file information char by char. It extends the InputStreamReader class.

Creating FileReader Class

Here is how we can create a FileReader:

Using the name of the file
Syntax : FileReader input = new FileReader(String name);

Using an Object of the file
Syntax : FileReader input = new FileReader(File fileObj);

Example: Program to understand FileReader class in Java
import java.io.*;
public class FRDemo 
{
    public static void main(String args[]) throws Exception{    
          FileReader fr=new FileReader("file.txt");    
          int i;    
          while((i=fr.read())!=-1)    
          System.out.print((char)i);    
          fr.close();    
    } 
}
Methods of FileReader class in Java
  1. read(): reads a single character from the reader
  2. read(char[] array): reads the characters from the reader and stores them in the specified array
  3. read(char[] array, int start, int length): reads the number of characters equal to length from the reader and stores in the specified array starting from the start.
  4. getEncoding(): It can be used to get the type of encoding that is used to store data in the file.
  5. close() : To close the input stream reader, we can use the close() method. Once the close() method is called, we cannot use the reader to read the data.
  6. ready(): checks if the file reader is ready to be read
  7. reset(): returns the control to the point in the reader where the mark was set
FileWriter class in Java

This character stream class is used to write the content onto the file char by char.  It is used for file handling in java. It extends the OutputStreamWriter class.

Creating a FileWriter object
FileWriter fw = new FileWriter(“filename”); //overwrite
FileWriter fw = new FileWriter(“filename”, true); //append

Example: Program to understand FileWriter class in Java
import java.io.*;
public class FWDemo 
{
    public static void main (String args[]) throws IOException
    {
        FileWriter fw = new FileWriter ("output.txt");
        String str = "This time never come back";
        fw.write (str);
        char chars[] = str.toCharArray ();
        fw.write (chars);
        for (int i = 0; i < str.length (); i++)
        {
         fw.write (str.charAt (i));
        }
        fw.flush ();
        fw.close ();
        System.out.println ("Success");
    }
}

Output: Success
Output.txt
This time never come backThis time never come backThis time never come back

Methods of FileWriter Class in Java
  1. write(): writes a single character to the writer
  2. write(char[] array): writes the characters from the specified array to the writer
  3. write(String data): writes the specified string to the writer
  4. close() : To close the file writer, we can use the close() method. Once the close() method is called, we cannot use the writer to write the data.
  5. flush(): forces to write all the data present in the writer to the corresponding destination
BufferedReader class in Java

This is a character stream class which is used to perform reading operation from any input device like keyboard, file, etc.  It makes the performance fast. It inherits the Reader class.

During the read operation in BufferedReader, a chunk of characters is read from the disk and stored in the internal buffer. And from the internal buffer characters are read individually. Hence, the number of communication to the disk is reduced. This is why reading characters is faster using BufferedReader.

Creating BufferedReader Object: BufferedReader buffer = new BufferedReader (Reader obj);

Example: Program to understand BufferedReader Class
import java.io.*;
public class BRDemo 
{
    public static void main(String[] args) throws IOException {
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  System.out.println("Enter your name");
  String name = br.readLine();
  System.out.println("Welcome " + name);
 }
}

Output:
Enter your name
Anurag
Welcome Anurag

BufferedWriter Class in Java

The BufferedWriter class of the java.io package can be used with other writers to write data (in characters) more efficiently. It extends the abstract class Writer. It makes the performance fast. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.

Creating BufferedWriter Object: BufferedWriter buffer = new BufferedWriter (file);

Example: Program to understand BufferedWriter Class in Java
import java.io.*;
public class BWDemo 
{
    public static void main(String[] args) throws Exception 
    {     
        FileWriter writer = new FileWriter("file.txt");  
        BufferedWriter buffer = new BufferedWriter(writer);  
        buffer.write("Welcome to Java Programming Language.");  
        buffer.close();  
        System.out.println("Success");  
    }  
}

Output: Success
file.txt
Welcome to Java Programming Language.

StringReader Class in Java

Java StringReader class is a character stream with string as a source. It takes an input string and changes it into the character stream. It inherits the Reader class. In StringReader class, system resources like network sockets and files are not used, therefore closing the StringReader is not necessary.

Creating StringReader Object: StringReader input = new StringReader(String data);

Example: Program to understand StringReader Class in Java
import java.io.StringReader;
public class SRDemo 
{
    public static void main (String[]args)
    {
        String data = "This is the text read from StringReader.";

        // Create a character array
        char[] array = new char[100];

        try
        {
            // Create a StringReader
            StringReader input = new StringReader (data);

            //Use the read method
            input.read (array);
            System.out.println ("Data read from the string:");
            System.out.println (array);

            input.close ();
        }
        catch (Exception e)
        {
            e.getStackTrace ();
        }
    }
}

Output:
Data read from the string:
This is the text read from StringReader.

StringWriter Class in Java

Java StringWriter class is a character stream that collects output from string buffer, which can be used to construct a string. The StringWriter class inherits the Writer class. In the StringWriter class, system resources like network sockets and files are not used, therefore closing the StringWriter is not necessary.

Creating StringWriter Object: StringWriter input = new StringWriter(int data);

Example: Program to understand StringWriter Class in Java
import java.io.StringWriter;
public class Main
{
    public static void main (String[]args)
    {
         String data = "This is the text in the string.";

        try {
            // Create a StringWriter with default string buffer capacity
            StringWriter output = new StringWriter();

            // Writes data to the string buffer
            output.write(data);

            // Prints the string writer
            System.out.println("Data in the StringWriter: " + output);

            output.close();
        }
        catch(Exception e) {
            e.getStackTrace();
        }
    }
}

Output: Data in the StringWriter: This is the text in the string.

In the next article, I am going to discuss the Java Serialization and Deserialization in detail with examples. Here, in this article, I try to explain Character Streams in Java with Examples. I hope you enjoy this Java Character Streams with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Java Character Streams with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *