简体   繁体   中英

Read txt file from resources folder in sub project Spring

Am trying to read a file from a subproject sample-dfx-sbi

file is located inside src/main/resources folder

exact file location is src/main/resources/wm/device.txt

Am using below logic to read file

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

    ...

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)

When I go to above location inside workspace and extract jar file I can see wm/device.txt

Then why is file not loading ?

Read resource as stream when you are binding it in 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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