You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何用命令行参数给Scanner传参并实现文件相对路径访问

问题原因

Java中使用File类创建文件对象时,传入的相对路径是基于运行Java程序时的当前工作目录,而非你的项目根目录或源代码所在目录。举个例子:如果你的项目根目录是my-project,但你在my-project/target目录下运行java Main test.txt,程序会在target目录下找test.txt,而非项目根目录下的文件,自然会抛出找不到文件的异常。

解决方案

方案1:自动推导项目根目录(推荐)

通过类加载器获取编译后的类文件根目录,再向上推导得到项目根,这样不管在哪台机器、哪个目录下运行程序,都能准确找到项目内的文件:

public static void main(String[] args) {
    try {
        // 获取编译后类文件的根目录(如target/classes)
        String classRoot = new File(Main.class.getResource("/").toURI()).getPath();
        // 向上两级目录得到项目根目录
        String projectRoot = new File(classRoot).getParentFile().getParent();
        // 拼接文件名,生成项目根下的文件对象
        File inputedFile = new File(projectRoot, args[0]);
        
        Scanner fileReader = new Scanner(inputedFile);
        while (fileReader.hasNextLine()) {
            String fileData = fileReader.nextLine();
            System.out.println(fileData);
        }
        fileReader.close();
    } catch (Exception e) {
        System.out.println("An error occurred when trying to open the file.");
        e.printStackTrace();
    }
}

方案2:固定运行目录

如果不想修改代码,可以明确要求用户必须在项目根目录下运行程序,执行命令示例:

java your.package.Main filename.txt

这种方式简单,但依赖用户操作规范,灵活性较差。

方案3:使用Java NIO Path API(Java 7+)

Java 7及以上版本推荐使用更健壮的NIO Path API处理文件路径,代码示例:

import java.nio.file.Paths;
import java.util.Scanner;

public static void main(String[] args) {
    try {
        String classRoot = new File(Main.class.getResource("/").toURI()).getPath();
        String projectRoot = new File(classRoot).getParentFile().getParent();
        // 使用Path API构建文件路径
        Scanner fileReader = new Scanner(Paths.get(projectRoot, args[0]));
        
        while (fileReader.hasNextLine()) {
            String fileData = fileReader.nextLine();
            System.out.println(fileData);
        }
        fileReader.close();
    } catch (Exception e) {
        System.out.println("An error occurred when trying to open the file.");
        e.printStackTrace();
    }
}
额外注意事项
  • 确认文件名拼写准确,注意大小写(Linux/macOS系统区分文件名大小写,Windows不区分)
  • 如果目标文件在项目的子目录中,需要传入相对于项目根的路径,比如data/input.txt

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:40:10