java配置文件路径
java配置文件路径写法
java程序中经常使用配置文件,将程序打成jar包后,配置文件的路径该如何设置,放于jar包内和外部时,代码如何写,在此做个记录。
测试代码
System.out.println(123);
System.out.println("user.dir:" + System.getProperty("user.dir"));
System.out.println("user.home:" + System.getProperty("user.home"));
//InputStream in = MainApp.class.getClassLoader().getResourceAsStream("config/config.ini");
String protectionDomain = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("protectionDomain:" + protectionDomain);
String path = System.getProperty("java.class.path");
System.out.println("java.class.path:" + path);
int firstIndex = path.lastIndexOf(System.getProperty("path.separator"))+1 ;
int lastIndex = path.lastIndexOf(File.separator) +1;
path = path.substring(firstIndex, lastIndex);
System.out.println("path:" + path);
System.out.println(321);
eclipse执行结果
![eclipse执行结果](https://img-blog.csdnimg.cn/2
jar包不同路径下执行结果
由此可见,使用user.dir设置配置文件路径并不是一个很好的解决办法,更好的应当选用protectionDomain,在程序和jar外部都可以方便使用。