Today Java Code Online is going to pick a very important topic, and that is regarding File Reading in Java. There are often various scenarios when the data required is to be read from a particular file that is not part of the application.
The external file may be a .txt, .xml, .csv etc. type of file. The thing that matters is that we need to read it in the Java application. The code discussed here is applicable for a .txt file. Though the processing will differ a bit for the other type of files.
I have taken an example, where a file is read from a particular folder. Replace the path with the path of your file, and you are all set to go. I have added extra comments for each line of code, so as to make there purpose clear in the Java Program.
The Java code is provided below:-
///////////////////////////////////////
package developer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException {
String fileStore = null;
//Note the "\\" used in the path of the file instead of "\",
//this is required to read the path in the String format.
FileReader fr = new FileReader("D:\\JavaCodeFile\\Test.txt");
BufferedReader br = new BufferedReader(fr);
//save the line of the file in a String variable and compare it with null, and continue till null (End of File) is not achieved
while(null != (fileStore = br.readLine()))
{
//Print the file line by line
System.out.println(fileStore);
}
//close the Buffered Reader
br.close();
//Close the File Reader
fr.close();
}
}
///////////////////////////////////////
When the code is executed, it will display the content of the file line by line on the console. for my case the output was as given below. Your output may differ based on the file content.
///////////////////////////////////////
Hello
Welcome to Java Code Online
This is a test file
///////////////////////////////////////
It should be enough to clear all your doubts for how to read a file in Java. If you liked the article then do leave a comment. Java Code Online will be coming up with more articles on file handling soon.
Thanks buddy for the Java code to read a file, the code was really useful to me.
ReplyDelete