温馨提示×

java相对路径怎么读取文件

小亿
83
2024-02-29 15:24:18
栏目: 编程语言

在Java中,可以使用相对路径来读取文件。相对路径是相对于当前工作目录或者类路径的路径。下面是一个简单的示例代码,演示如何使用相对路径读取文件:

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();
        }
    }
}

在上面的示例中,我们使用相对路径"file.txt"来读取文件。这里假设文件"file.txt"位于当前工作目录下。如果文件不存在或者路径错误,会抛出FileNotFoundException异常。

需要注意的是,相对路径是相对于当前工作目录的路径。如果需要读取类路径下的资源文件,则可以使用ClassLoader的getResourceAsStream方法来获取输入流。

0