关于在 java 应用程序中引用外部文件

About citing external files in java application

我正在编写一个 java 应用程序,我在其中自动在后台导入外部 csv 文件以进行计算。但问题是我在 java 程序中使用了 "absolute" 文件路径,生成的 jar 文件在另一台计算机上将无法运行。 java 中是否有使用某种 "working directory path" 的方法,这样只要我将要导入的 csv 文件放入,我仍然可以 运行 另一台计算机中的 jar 文件与 jar 文件相同的文件夹?

谢谢!

new File(".") 给你相对路径

你可以这样写相对路径:

File file = new File(".\CSVs\myfile.csv"); 

您可以使用文件名读取文件,例如

try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
    String line;
    while ((line=br.readLine())!=null) {
        System.out.println(line);
    }   
} catch (Exception e) {
    e.printStackTrace();
}

此处 text.txt 应位于执行 jar 的同一工作目录中。

您也可以使用命令行参数从命令行读取目录名称,例如

public static void main(String[] args) {

    //check if there were any command line arguments
    if (args.length > 0) {
        // args[0] is the first command line argument unlike C where args[0] would give u the executable's name
    } else {
        System.err.println("Usage: java -jar <jar_name> [directory_names..]");
    }
}

您还可以使用属性文件等配置文件来读取目录名称。

System.getProperty("user.dir") 将 return 你的工作目录。

System.getProperty("user.dir")+"\\myfile.txt"

更多信息在这里:system properties, oracle docs