Character Stream Classes

Character stream allows flow of information in the forms of characters. So in order to read content from character file, character stream is used. If we are using byte stream to read from a character file then after reading, content need to be converted to character. Character stream allow reading of characters from file without any conversion.

 
	        1. Open a Stream
2. Perform operation (Read/Write)
3. Close Stream

Now question is how to open a stream. For opening a stream we need to create an object of stream class. There are a number of byte stream classes.


Reader and Writer are abstract class. These classes can't be instantiated. Their child classes shown in diagram can be used for I/O operations.

1. Open a stream

For example we want to read from a file. then one stream is needed to be created. So for that FileReader class object has to be created.

Code :


  FileReader fis=new FileReader("one.txt");
	  

File name need to specified in the constructor of FileReader class. Above statement will create a stream between file one.txt and our program. Once stream is created, operation can be performed on stream.

2. Perform operation

In first step character stream is created, then read(char []) method will be called. read method for character stream will return character array.

Code :


FileReader fis=new FileReader("one.txt");
char data[]=new char[50];
fis.read(data);
for(char c:data)
System.out.print(c);

read() method will read file's content in an array. It will read content directly in character, so no need for explicit conversion.

3. Close the stream

For closing stream "close()" method is used.


 fis.close();
         


Complete program to read from file


import java.io.*;
class fileread
{
public static void main(String arg[])
{
try
{
FileReader fir=new FileReader("one.txt");
char []data=new char[50];
fir.read(data);
for(char c:data)
System.out.print(c);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Program to write to file


 import java.io.*;
class filewrite
{
public static void main(String arg[])
{
try
{
FileWriter fir=new FileWriter("one.txt");
fir.write("This is demo");
fir.flush();
fir.close();

}
catch(Exception e)
{
e.printStackTrace();
}
}
}