How to Read File From Resources in Java
This article will show how to read a file from resources in the Java programming language. All you need is a source file path.
How to Read File From Resources in Java
You can read any text file through the Java programming language. All you need to do is store a source path in a string and, using the try...catch
method, provide this path to a BufferedReader
. Look at the code below.
import java.io.*;
public class Main {
public static void main(String[] args) {
String sourcePath = "D:\\delftstack.txt"; // source file path To Read..
try {
BufferedReader Reader = new BufferedReader(new FileReader(sourcePath));
// Intializing Buffer Reader By Providing File path
String Data;
while ((Data = Reader.readLine()) != null) {
System.out.println(Data); // Reading Line By Line.....
}
Reader.close();
} catch (Exception e) {
}
}
}
We will explain the code line by line. First, store the source file path inside a string sourcepath
, copy your source path, and do the same. We use the try...catch
method because it returns an unhandled exception FileNotFoundException
.
We’ll pass the source path’s string into an object named BufferedReader
. It reads text from a character input stream. Learn more about BufferedReader
here.
We’ll store it inside a string using a while loop, whatever this buffer will read. All the data is read line by line and stored in a string. We are simply printing that string.
Make sure to write the correct source path and file name.
Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.
LinkedIn