Java多種獲取項目路徑下的文件方式
更新時間:2024年12月12日 15:38:42 作者:小目標青年
文章介紹了在Java項目中獲取resources文件夾下文件的InputStream的多種方法,包括使用類加載器、上下文類加載器、系統(tǒng)屬性和Paths類
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 ,該干嘛干嘛吧
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
java實現(xiàn)附件預覽(openoffice+swftools+flexpaper)實例
本篇文章主要介紹了java實現(xiàn)附件預覽(openoffice+swftools+flexpaper)實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-10-10MyBatisPlus的autoResultMap生成策略實現(xiàn)
本文主要介紹了MyBatisPlus的autoResultMap生成策略實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-02-02java面向國際化項目開發(fā)需遵循的命名規(guī)范
這篇文章主要為大家介紹了在參與開發(fā)國際化項目時需遵循的java命名規(guī)范,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03