简体   繁体   中英

Java reading text file in eclipse

I am trying to read a text file available in a different package but in same project but always getting InputStream as null.

public class ReadFileApp {

    public static void main(String[] args) {

        Thread currentThread = Thread.currentThread();
        ClassLoader classLoader = currentThread.getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("/com/rpsoft/response/fileOneResponse.txt");

        String response = null;
        try {
            response = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Current Thread : " + currentThread);
        System.out.println("Class Loader : " + classLoader);
        System.out.println("InputStream : "+ inputStream);
        System.out.println("Response : " + response);
    }
}

Getting Exception :

Exception in thread "main" java.lang.IllegalArgumentException: No InputStream specified
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:106)
    at org.springframework.util.FileCopyUtils.copyToByteArray(FileCopyUtils.java:156)
    at com.rpsoft.filetransport.ReadFileApp.main(ReadFileApp.java:18)

You can try any one based on the file location in the project.

// Read from same package 
getClass().getResourceAsStream("fileOneResponse.txt")

// Read from resources folder parallel to src in your project
new File("resources/fileOneResponse.txt")

// Read from src/resources folder
getClass().getResource("/resources/fileOneResponse.txt")

// Read from src/resources folder
getClass().getResourceAsStream("/resources/fileOneResponse.txt")

Try removing the leading slash from the resouce name.

classLoader.getResourceAsStream("com/rpsoft/response/fileOneResponse.txt");

instead of

classLoader.getResourceAsStream("/com/rpsoft/response/fileOneResponse.txt");

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