Friday, July 19, 2013

FileReader vs. FileWriter

FileReader is a class for reading characters file. A characters file stores characters. One character is equivalent to one byte. In contrast, FileWriter writes a characters or many characters to the characters file.

FileReader constructor:
-FileReader(String filename)
-FileReader(File file)
Its useful methods:
-read():int
-read(char[] cs)

FileWriter constructors:
-FileWriter(String filename)
-FileWriter(File file)
-FileWriter(String filename, boolean append)
-FileWriter(File file, boolean append)

Its useful methods:
-write(int byte):void
-write(char[] cs):void
-write(Stirng st):void

In the example below, the FileWriter object is created by passing the file path (desc) to write the data to. Its write(String st) method is used to write text to the file. If you wan to write a single byte to the file at a time, you will use write(int byte) instead. You also can write an array of characters to the file by using the write (char[] cs) method. The flush method is used after the write method to immediately flush data to the file.
To read the data back from the file, the readText method is called. Inside the readText method, the FileReader object is created. Its accepts a string of file path to read from. You can read one character at a time by using the read() method or you can read many characters at a time by using the read(char[] cs) method. In this example, we want to read all characters at a time from the file. So the array that will used to store the content of the file must have its size equal to the length of the file. You can get the length of the file by using the length() method of the File object.

import java.io.*;

public class Example{

public static void main(String[] args){
writeText("Hello, world!","testfile.txt");
readText("testfile.txt");
}

public static void writeText(String text,String desc) throws IOException{

FileWriter fw=new FileWriter(desc); //create writer
fw.write(text); //write text to the file
fw.flush();
fw.close();
}
public static void readText(String src) throws IOException{
FileReader fr=new FileReader(src); //create reader
File f=new File(src); //create file object to connect to the file on local disk
char[] cs=new char[(int)f.length()]; //create char array to store characters
fr.read(cs); //read characters from file and store them in the array
System.out.println(cs); //output the characters on the screen
fr.close();

}
}

No comments:

Post a Comment