Files Read/Write
Read a File:
We can also read the contents of a file in Java. This is done using the Scanner
class. This method throws a FileNotFoundException
if any error occurs. Hence it is important to write it in a try...catch block.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("students.txt");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("Error.....");
e.printStackTrace();
}
}
}
Output:
Here we do not see an output, because the students.txt
file created has no content. Let’s read a file which has some content in it.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
File file = new File("Teachers.txt");
Scanner myReader = new Scanner(file);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("Error.....");
e.printStackTrace();
}
}
}
Output:
This file has information of Teachers
Name: Rosy Fernandes, Age: 36
Name: Isha Mheta, Age: 29
Write a File:
We use the FileWriter
class to write into a file in Java.
Example:
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try {
FileWriter file = new FileWriter("Teachers.txt");
file.write("This file has information of Teachers");
file.write("Name: Rosy Fernandes, Age: 36");
file.write("Name: Isha Mheta, Age: 29");
file.close();
System.out.println("File has been written into.");
} catch (IOException e) {
System.out.println("Error......");
e.printStackTrace();
}
}
}
Output:
File has been written into.