We will read c:/myFile.txt
c:/myFile.txt looks like this >
You are learning File IO from javaMadeSoEasy.com
|
BufferedReader's read() method will read 1 character (2byte / 16-bit) at a time.
Program 1 to Read text from file using FileReader’s read() in java file IO >
import java.io.FileReader;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class ReadFileUsingFileReader {
public static void main(String... args) {
FileReader fr = null;
try {
fr = new FileReader("c:/myFile.txt");
System.out.println("Reading from text file using FileReader > ");
int ch;
while ((ch = fr.read()) != -1) { //read till end of file
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close(); //close FileReader
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
Reading from text file using FileReader >
You are learning File IO from javaMadeSoEasy.com
*/
|
Program 2 to Read text from file using FileReader’s read(charArray) method in java file IO >
import java.io.FileReader;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class ReadFileUsingFileReader {
public static void main(String... args) {
FileReader fr = null;
try {
fr = new FileReader("c:/myFile.txt");
System.out.println("Reading from text file using FileReader > ");
char[] charArray = new char[1000];
fr.read(charArray); // reads the content of file in the array
for (char ch : charArray)
System.out.print(ch); // display all the characters one by one
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr != null)
fr.close(); //close FileReader
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
Reading from text file using FileReader >
You are learning File IO from javaMadeSoEasy.com
*/
|
RELATED LINKS>
Program to Write to file using FileWriter in java file IO
Program to Write byteArray to file using FileOutputStream in java file IO
Difference between FileInputStream and BufferedInputStream in java file IO
Program to Move a file - in java file IO
Program to Rename a file - in java file IO
Labels:
Core Java
File IO/File handling