I have a text file in which I have stored some text data which describes the areas of Colombo which is also known as the Commercial capital of Sri Lanka. I need to read the data from a text file and display on screen with a different format.
There are many ways to reach this target. Here I have used BufferedReader to read the file line by line using a FileReader.
My project structure is as below.
Below is the text file (Colombo.txt)
So, here is the solution
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("Colombo.txt"));
try{
String num;
String englishName;
String nativeName;
String readLine = br.readLine();
while (readLine != null){
num = readLine.split(",")[0];
englishName = readLine.split(",")[1];
nativeName = readLine.split(",")[2];
System.out.println("Colombo " + num + " - " + englishName + " - " + nativeName );
readLine = br.readLine();
}
}finally {
if(br != null){
br.close();
}
}
}
}
Let me explain the concept behind the try-with-resources statement in Java which is introduced in Java 7
The try-with-resources statement is a try statement that
declares one or more resources .
A resource is an object that must be closed after the
program is finished with it.
This statement ensures that each resource is closed at the
end of the statement.
Coming back to our example, let me put the above challenge in a much cleaner way using try-with-resources statement instead of a try statement.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
try(BufferedReader br = new BufferedReader(new FileReader("Colombo.txt"))){
String num;
String englishName;
String nativeName;
String readLine = br.readLine();
while (readLine != null){
num = readLine.split(",")[0];
englishName = readLine.split(",")[1];
nativeName = readLine.split(",")[2];
System.out.println("Colombo " + num + " - " + englishName + " - " + nativeName );
readLine = br.readLine();
}
}
}
}
As you can see, I have declared the BufferedReader as a resource which doesn't need to be closed at the finally block explicitly. This reduces several lines of code and makes the code simpler.
Output
I hope it was useful...