目錄
1.獲取方式1
2.示例1
3.獲取方式2
4.示例2
1.獲取方式1
使用ClassPathResource獲取路徑下的文件。
一般來說,我們項(xiàng)目的配置文件及靜態(tài)資源都會放置在resources目錄下。有時(shí)我們在項(xiàng)目中使用到resources目錄下的文件,這時(shí)我們可以使用Spring下的Resouce接口來讀取。具體代碼如下
Resource resource = new ClassPathResource(“static/Std_Resource_Train_Model.xls”);
// 因?yàn)镽esouce是一個(gè)接口 所以我們可以使用它的實(shí)現(xiàn)類ClassPathResource來new一個(gè)對象。而構(gòu)造方法的參數(shù)便是resources目錄下的文件路徑,注意這里是使用的相對路徑(相對于resouces目錄而言的)。
2.示例1
文件位置
service層文章來源:http://www.zghlxwxcb.cn/news/detail-507978.html
public void export() throws IOException {
// String path = "classpath:templates/shelfimport.xlsx";
// InputStream inputStream = new ClassPathResource("templates/shelfimport.xlsx").getInputStream();
//
String path1 = new ClassPathResource("templates/shelfimport.xlsx").getPath();
String filename = new ClassPathResource("templates/shelfimport.xlsx").getFilename();
InputStream inputStream = new ClassPathResource("templates/shelfimport.xlsx").getInputStream();
DynamicHeaderListener listener = new DynamicHeaderListener();
EasyExcel.read(inputStream, listener).sheet().headRowNumber(1).doReadSync();
List<Map<Integer, String>> list = listener.getList();
list.forEach(item -> {
item.forEach((k,v)->{
System.out.println(k);
System.out.println(v);
});
});
// System.out.println(path);
System.out.println(path1);
System.out.println(filename);
// String path1 = this.getClass().getResource("templates/shelfimport.xlsx").getPath();
// System.out.println(path1);
}
3.獲取方式2
使用當(dāng)前類的getClass方法獲取相應(yīng)的文件。文章來源地址http://www.zghlxwxcb.cn/news/detail-507978.html
4.示例2
String path = "template/shelfimport.xlsx";
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path);
DanyListener danyListener = new DanyListener();
EasyExcel.read(resourceAsStream, danyListener).sheet(0).headRowNumber(1).doRead();
List<HashMap<Integer, String>> dataList = danyListener.getDataList();
dataList.forEach((item) -> {
item.forEach((K, V) -> {
System.out.println(K);
System.out.println(V);
});
});
到了這里,關(guān)于Java中獲取某個(gè)目錄下文件的方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!