Skip to content

How to read file from relative path in Java project? java.io.File cannot find

To read a file from a relative path in a Java project, you can use the File class from the java.io package and specify the relative path to the file.

Here's an example of how to read a file from a relative path in a Java project:


java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    try (Scanner scanner = new Scanner(new File("src/main/resources/data.txt"))) {
      while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        System.out.println(line);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}

In this example, the File class is used to open the file at the relative path src/main/resources/data.txt. The Scanner class is then used to read the contents of the file line by line.

The relative path of the file is relative to the working directory of the Java application. In modern Java projects (Maven/Gradle), files in src/main/resources are typically copied to the classpath during the build process, so accessing them via java.io.File may fail unless you run the application from the project root. You can use the user.dir system property to verify the working directory:


java
System.out.println(System.getProperty("user.dir"));

If the File class cannot find the file at the specified path, it will throw a FileNotFoundException. You can catch this exception and handle it appropriately.

I hope this helps! Let me know if you have any questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.