How to Read File From Resources in Java

Haider Ali Feb 02, 2024
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.

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.....
    } 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.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

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.


Related Article - Java File