繁体   English   中英

从子项目Spring的资源文件夹中读取txt文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM