FileReader
- to read characters data or text data.
- Here, we can read character by character by character; not line by line.
Constructors
FileReader fr = new FileReader(String fileName);
FileReader fr = new FileReader(File f);
If no file is available, this will throw exception.
Methods
int read ()
- Unicode value of character.
int read (char[] ch)
- no of characters copied from file into array.
void close()
Examples
Text File
Hello my name is Arjun.
Read File By Looping
- Demo of a FileReader class.
import java.io.FileReader; import java.io.IOException; class FileReaderDemo{ // Method : int read() public static void main(String[] args){ try{ FileReader fr = new FileReader("myText.txt"); int i = fr.read(); while(i != -1){ // Denotes no character System.out.print((char)i); // Type-hinting i = fr.read(); } fr.close(); }catch(IOException error){ error.printStackTrace(); } } }
Read File With Character Array
- Demo of a FileReader class using a array.
import java.io.*; class FileReaderDemo{ public static void main(String[] args){ try{ // Method : int read(char[] ch) File f = new File("myText.txt"); // Dynamically allocating the size of the array according to the text length inside file. char[] ch = new char[(int)f.length()]; FileReader fr = new FileReader(f); fr.read(ch); // Assigns each character into another character variable. for(char ch1:ch){ System.out.print(ch1); } fr.close(); }catch(IOException error){ error.printStackTrace(); } } }