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

时间:2018-03-30 05:42:07

标签: java spring-mvc

我试图从子项目中读取文件 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

那为什么文件没有加载?

1 个答案:

答案 0 :(得分:1)

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;
}