[英]Check if a file exists in the same directory as the jar file
我知道如何檢查特定目錄或特定目錄中的文件,但我無法弄清楚如何檢查正在運行的jar之外但與它在同一目錄中的文件:Test.jar - Ran - >獲取Test.file Test.file的位置
回答 - 謝謝!
這很好用;
final Class<?> referenceClass = Client.class;
final URL url = referenceClass.getProtectionDomain().getCodeSource().getLocation();
try{
final File jarPath = new File(url.toURI()).getParentFile();
System.out.println(jarPath);
} catch(final URISyntaxException e){
// etc.
}
您可以使用createNewFile()操作創建新文件,獲取該文件的位置並再次刪除該文件。 新文件將在與運行jar文件的位置相同的位置生成。
在此線程中使用ProtectionDomain
提供了一個可能的解決方案: 相對於正在執行的jar文件加載文件
JAR文件的位置由Class.getProtectionDomain().getCodeSource().getLocation()
為已知在該JAR文件中的任何類提供。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.