我想将文件保存在与应用程序 jar 文件位于同一位置的文件夹中。我试图通过以下方式实现这一目标:
private String checkFolder() throws URISyntaxException {
String path=new File(MigrationsApplication.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath()+"\\MigrationFiles";
System.out.println("PATH2:"+path);
File file=new File(path);
if(!file.exists()){
boolean folderCreated = file.mkdir();
if(folderCreated){
System.out.println("The folder MigrationFiles was created");
}
}
return path;
}
如果我从 Intellij 运行项目,返回的路径是 C:\Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\target\classes\
,如果我从命令行运行它,返回是 \Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\out\artifacts\Migrations_jar\Migrations.jar
.这是应该发生的吗?另外我如何才能将 jar 路径仅返回到 \artifacts\Migrations_jar
?
答案 0 :(得分:2)
本质上,.jar
文件是捆绑的 classes
目录。
可以测试返回的值是否是目录,如果是则去掉文件名。
Path p = Path.of(path);
if(! p.isDirectory()) {
p = p.getParent();
}
return p.toString();