Java Relative Path File Reading

In Java, you can use relative paths to read files. Relative paths are paths that are relative to the current working directory or classpath. Below is a simple example code demonstrating how to read a file using a relative path:

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

public class Main {
    public static void main(String[] args) {
        // 相对路径,相对于当前工作目录
        String filePath = "file.txt";
        
        try {
            File file = new File(filePath);
            Scanner scanner = new Scanner(file);
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到:" + filePath);
            e.printStackTrace();
        }
    }
}

In the above example, we use the relative path “file.txt” to read the file. It is assumed here that the file “file.txt” is located in the current working directory. If the file does not exist or the path is incorrect, a FileNotFoundException exception will be thrown.

It is important to note that a relative path is determined in relation to the current working directory. If you need to access a resource file within the classpath, you can use the getResourceAsStream method of ClassLoader to obtain an input stream.

bannerAds