Character streams in Java


Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.

The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Following are the character array stream classes provided by Java −

ReaderWriter
BufferedReaderBufferedWriter
CharacterArrayReaderCharacterArrayWriter
StringReaderStringWriter
FileReaderFileWriter
InputStreamReaderInputStreamWriter
FileReaderFileWriter

Example

The following Java program reads data from a particular file using FileReader and writes it to another, using FileWriter.

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOStreamsExample {
   public static void main(String args[]) throws IOException {
      //Creating FileReader object
      File file = new File("D:/myFile.txt");
      FileReader reader = new FileReader(file);
      char chars[] = new char[(int) file.length()];
      //Reading data from the file
      reader.read(chars);
      //Writing data to another file
      File out = new File("D:/CopyOfmyFile.txt");
      FileWriter writer = new FileWriter(out);
      //Writing data to the file
      writer.write(chars);
      writer.flush();
      System.out.println("Data successfully written in the specified file");
   }
}

Output

Data successfully written in the specified file

Updated on: 15-Oct-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements