我正在尝试创建一个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);
}
只需替换以下行:
File file = new File("/com/configuration/settings.properties");
with:
File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");
相对路径取决于您正在运行程序的当前工作目录。
如果您正在IDE运行,IDE可能会将工作目录路径设置为项目目录。以及您的程序的运行方式取决于程序中的class路径。