![](/img/trans.png)
[英]Read txt file from resources folder on maven Quarkus project From Docker Container
[英]Read txt file from resources folder in sub project Spring
我正在嘗試從子項目sample-dfx-sbi中讀取文件
文件位於src / main / resources文件夾內
確切的文件位置是src / main / resources / wm / device.txt
我正在使用以下邏輯讀取文件
static final ClassLoader loader = DummyClass.class.getClassLoader();
public void getData(String ip)throws IOException {
String filepath = loader.getResource("/wm/device.txt").toString();
System.out.println(filepath);
File file = new File(filepath);
FileReader fileReader = new FileReader(file); // exception
...
例外:
jar:file:/home/user/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sample-dfx-web/WEB-INF/lib/sample-dfx-sbi-0.0.1-SNAPSHOT.jar!/wm/device.txt
java.io.FileNotFoundException: jar:file:/home/user/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sample-dfx-web/WEB-INF/lib/sample-dfx-sbi-0.0.1-SNAPSHOT.jar!/wm/device.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
當我轉到工作空間內的上述位置並提取jar文件時,我可以看到wm / device.txt
那為什么不加載文件呢?
在JAR
中綁定資源時,將其作為流讀取。
public String loadResource(String filelocation) {
if (filelocation != null && !filelocation.trim().isEmpty()) {
try (
InputStream inputStream = getClass().getResourceAsStream(filelocation);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));) {
String fileLine = "";
StringBuffer stringBuffer = new StringBuffer();
while((fileLine = bufferedReader.readLine())!= null){
stringBuffer.append(fileLine);
}
return stringBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.