How to read file from relative path in Java project? java.io.File cannot find the path specified
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:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("src/main/resources/data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} 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. You can use the user.dir
system property to get the working directory of the application and construct the relative path based on that.
For example:
File file = new File(System.getProperty("user.dir") + "/src/main/resources/data.txt");
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.