[英]Specify a Relative Path from a Package for a new File
我试图创建一个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);
}
相对路径取决于运行程序的当前工作目录。
如果您在IDE中运行,IDE可能会将工作目录路径设置为Project目录。 程序的运行方式取决于程序中jar / clases的类路径。
只需替换此行:
File file = new File("/com/configuration/settings.properties");
与:
File file = new File(new File(Thread.currentThread().getContextClassLoader().getResource("").toURI()), "com/configuration/settings.properties");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.