0

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)
1
  • Seems that your file doesn't exist. Commented Jun 17, 2014 at 17:04

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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");

1 Comment

Thanks it's solved exactly as you have mentioned above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.