【发布时间】:2011-11-08 09:35:53
【问题描述】:
如何以最简洁的方式访问与 jar 文件(不在其中)相邻的文件?
我尝试了各种组合,例如 File configFile = new File("..//pinger.properties"); 和 Pinger.class.getResourceAsStream("pinger.properties");,但没有读取文件。
谢谢!
【问题讨论】:
如何以最简洁的方式访问与 jar 文件(不在其中)相邻的文件?
我尝试了各种组合,例如 File configFile = new File("..//pinger.properties"); 和 Pinger.class.getResourceAsStream("pinger.properties");,但没有读取文件。
谢谢!
【问题讨论】:
您可以尝试使用java.util.Properties 类。
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("pinger.properties"));
另一个示例是here。
【讨论】:
如何以最简洁的方式访问与 jar 文件(不在其中)相邻的文件?
添加一个使用相对路径1引用依赖 Jar 的清单文件。然后使用getResource(String) 获取资源的URL。
【讨论】:
获取 jar 文件的位置
考虑以下函数
public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
假设你的 jar 文件在 D:\Test\dist
然后 path() 将返回 /D:/Test/dist/filename
【讨论】: