【问题标题】:Specify a Relative Path from a Package for a new File为新文件指定包中的相对路径
【发布时间】:2012-12-13 18:45:56
【问题描述】:

我正在尝试创建一个File 对象以保存我的属性文件。我需要知道如何从我的包中指定相对路径,因为下面的代码不起作用。

    try {
        File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            properties.store(fileOutputStream, null);
        }
    } catch (IOException | URISyntaxException ioe) {
        System.out.println(ioe);
    }

【问题讨论】:

标签: java file properties package relative-path


【解决方案1】:

只需替换这一行:

File file = new File("/com/configuration/settings.properties");

与:

File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");

【讨论】:

  • 该文件将出现在您的 bin 文件夹下。
【解决方案2】:

相对路径取决于您运行程序的当前工作目录。

如果您在 IDE 中运行,IDE 可能会将工作目录路径设置为项目目录。而你的程序如何运行取决于你程序中 jar/claases 的类路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2021-08-16
    • 2013-04-16
    相关资源
    最近更新 更多