Reputation: 1
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);
}
}
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)
Upvotes: 0
Views: 244
Reputation: 4523
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");
Upvotes: 0
Reputation: 46841
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")
Upvotes: 1