Lab-16
Lab-16
Objective:
• To understand File Input Output in java
• To learn the uses of FileWriter, FileReader, BufferedWriter, BufferedReader for file
handling
• To learn the uses of different files in Java
File Input
We need total 3 things for the file input operation:
1. File path and name
2. FileWriter Object (it will take the file path inside the parameter of constructor invocation)
3. BufferedWriter (it will take the FileWriter object inside the parameter of constructor
invocation)
Now, to write on a file, we need to use the BufferedWriter objects write method. The FileWriter and
BufferedWriter objects must be created inside a try-catch block to ignore any IOException.
Finally, we need to close the BufferedWriter object to terminate the file writing.
try {
FileWriter fw = new FileWriter(filePath);
BufferedWriter writer = new BufferedWriter(fw);
writer.write("Hello File!");
writer.write("\Another File!");
System.out.println("Writing done!");
try {
FileReader fr = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fr);
String line;
System.out.println("Reading from file:");
while((line = reader.readLine())!=null){
System.out.println(line);
}
reader.close();
Program Output:
ID:113098
mark:20
ID:115089
mark:15
ID:345678
mark:12
ID:234566
mark:18
Highest mark obtained by ID:113098