在 Jar 位置保存文件
Saving a file at the Jar location
我想将文件保存在与应用程序 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 的项目,returned 的路径是 C:\Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\target\classes\
如果我 运行 它来自命令行 return 是 \Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\out\artifacts\Migrations_jar\Migrations.jar
.这应该发生吗?另外我怎么才能 return jar 路径只到 \artifacts\Migrations_jar
?
本质上,.jar
文件是捆绑的 classes
目录。
您可以测试返回的值是否为目录,如果是则去掉文件名。
Path p = Path.of(path);
if(! p.isDirectory()) {
p = p.getParent();
}
return p.toString();
我想将文件保存在与应用程序 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 的项目,returned 的路径是 C:\Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\target\classes\
如果我 运行 它来自命令行 return 是 \Users\fabio\OneDrive\Ambiente de Trabalho\Migrations\out\artifacts\Migrations_jar\Migrations.jar
.这应该发生吗?另外我怎么才能 return jar 路径只到 \artifacts\Migrations_jar
?
本质上,.jar
文件是捆绑的 classes
目录。
您可以测试返回的值是否为目录,如果是则去掉文件名。
Path p = Path.of(path);
if(! p.isDirectory()) {
p = p.getParent();
}
return p.toString();