FileReader
It is used for reading streams of characters.
Syntax for java.io.FileReader class:
public class FileReader extends InputStreamReader
Example:
Create a text file named text5 inside a folder(here FileExamples) in D drive with following data(Any data can be written):
Amitabh Bachchan is a great actor!!
Save the file and then run the program.
Example :
Com.knowledge2life
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
OUTPUT:
Read file( Knowledge2life.txt)
FileWriter
It is used for writing streams of characters.
Syntax for Java.io.FileWriter class:
public class FileWriter extends OutputStreamWriter
Example :
Com.knowledge2life
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("knowledge2life.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
OUTPUT:
File created: Knowledge2life.txt