These
two classes are used to read and write data from a file as characters. It is
recommended to use FileReader and FileWriter classes to read data from text
file where as FileInputStream and FileOutputStream classes are only recommended
to read and write image files.
FileReader –
Constructors of FileReader –
1.
FileReader(String name)
2.
FileReader(File f)
Methods of FileReader –
1. int
read() – It attempts to read next character from the file and returns its
Unicode value. If the next character isn’t available, then we will get -1 i.e., it returns -1.
2. int
read(char[] ch) – It attempts to read enough characters from the file into the
char[] array and returns the number of characters copied.
3. void
close()
Example –
import
java.io.File;
import
java.io.FileReader;
import
java.io.IOException;
public class
Read1 {
public static void
main(String[] args) throws IOException{
File f = new
File("xyz.txt");
FileReader
fr = new
FileReader(f);
char[]
ch = new char[(int)f.length()];
fr.read(ch);
for(char ch1:ch)
{
System.out.print(ch1);
}
fr.close();
}
}
Output –
i love coding
i love java
i am a hacker
FileWriter-
Constructors of FileWriter –
1.
FileWriter(String s)
2.
FileWriter(String name,boolean append)
3.
FileWriter(File f,boolean append)
Methods of FileWriter –
1. write(int
i) – To write a single character to the file.
2.
write(char[] ch) – To write an array of character to the file.
3.
write(String s) – To write a string to the file
4.
flush() – To give guarantee that the last character of the data is added to the
file.
5.
close() – close the file.
Example –
import
java.io.FileWriter;
import
java.io.IOException;
public class
Read1 {
public static void
main(String[] args) throws IOException{
FileWriter
fw = new
FileWriter("xyz.txt");
fw.write("Welcome to Coding makes perfect");
fw.write("\n");
fw.write("Lets code");
fw.write("\n");
fw.write("Guwahati");
fw.write("\n");
char ch[] = {'A','S','S','A','M'};
fw.write(ch);
fw.flush();
fw.close();
System.out.println("Data succesfully written into the file");
}
}
Output –
Data succesfully written into
the file
Limitations with FileReader and FileWriter –
While
writing data by using FileWriter, we have to insert separator(mandatory) which
is valid from OutputStream to OutputStream, hence it is overhead to the
programmer. While reading the data by using FileReader we have to read
character by character which isn’t convenient to the programmer and it isn’t
recommended with respect to performance. To overcome these problems we should
go for BufferedWriter and BufferedReader.
No comments:
Post a Comment