Java 从包中为新文件指定相对路径

Java 从包中为新文件指定相对路径,java,file,properties,package,relative-path,Java,File,Properties,Package,Relative Path,我试图创建一个文件对象以保存我的属性文件。我需要知道如何从我的包中指定相对路径,因为下面的代码不起作用 try { File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties"); try (FileOutputStream fileO

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

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

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


若您在IDE中运行,IDE可以将工作目录路径设置为项目目录。程序的运行方式取决于程序中jar/claases的类路径。

只需替换这一行:

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


你试过这个吗?该文件将显示在您的bin文件夹下。
File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");