java多种获取项目路径下的文件
目标文件放在项目的resources文件夹下 的 mytxt文件里面
文件名叫 file test.txt
其实可以看到,项目运行后
这个文件被丢到了target文件夹下
拿到这个文件的 inputstream
比如我们在fileutil里面写个获取文件流的方法
public class fileutil { }
① getresourceasstream
string filepath = "/mytxt/filetest.txt"; inputstream inputstream = fileutil.class.getresourceasstream(filepath);
② getresource + getpath
string filepath = "/mytxt/filetest.txt"; string path = fileutil.class.getresource(filepath).getpath(); inputstream fileinputstream = new fileinputstream(path);
③ getclassloader().getresourceasstream
注意了:
这种方式文件路径path初始不带 / 杠
string filepath = "mytxt/filetest.txt"; inputstream inputstream = fileutil.class.getclassloader(). getresourceasstream(filepath);
④ thread.currentthread().getcontextclassloader().getresource
注意了:
这种方式文件路径path初始不带 / 杠
string filepath = "mytxt/filetest.txt"; string path = thread.currentthread().getcontextclassloader(). getresource(filepath ).getpath(); inputstream fileinputstream = new fileinputstream(path);
⑤ system.getproperty
先拿项目根路径,再拼接target/classes 以及 文件路径
string filepath = "/mytxt/filetest.txt"; string relativelypath = system.getproperty("user.dir"); inputstream fileinputstream = new fileinputstream(relativelypath + "/target/classes/" + filepath);
⑥ paths.get("").toabsolutepath()
先拿项目根路径,再拼接target/classes 以及 文件路径
string filepath = "/mytxt/filetest.txt"; path path = paths.get("").toabsolutepath(); inputstream fileinputstream = new fileinputstream(path + "/target/classes/" + filepath);
拿到inputstream ,该干嘛干嘛吧
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论