java读取resources目录和同级目录文件
1.读取resource目录下的文件
/** * 读取resource中的文件 */ private static void readcurrent() { try { inputstream in = filepath.class.getresourceasstream("/a.properties"); properties properties = new properties(); properties.load(in); system.out.println(properties.getproperty("name")); system.out.println(properties.getproperty("password")); } catch (exception e) { e.printstacktrace(); } }
2.读取jar包同级目录下的文件
public static void readfile() { try { string path = system.getproperty("user.dir") + "/a.properties"; file file = new file(path); if (file.isfile()) { system.out.println("找到文件"); } else { system.out.println("未找到相应文件"); } } catch (exception e) { } }
在ide中运行的没有问题,但是发布之后发现了问题,user.dir和java -jar命令执行程序所在目录有关系
然后写个测试样例测试一下,发现和执行目录有关系,如果想使用user.dir这个方法,就要注意jar运行的目录问题。
public static void main(string[] args) { string usedir = system.getproperty("user.dir"); system.out.println(usedir); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论