I'm trying to read in file content, ex :
public void myMethod(){
FileInputStream fstream = new FileInputStream(fileLocation);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
....
....
.....
end while
end method
And I have at the begining of the class body private String fileLocation;
and at the end of a class I have a getter and setter for it. Now I'm trying inject this file location from spring inside bean from this class and I specify the init-method of this class. But I get error cannot find the specified file as if its not on a classpath but it is inside war file? I'm building the project with maven and I put file in src/main/resources
This is the error I get when trying to read file :
Error: srcmain
esourcesids.txt
(The system cannot find the path
specified)
That is when I tried this :
FileInputStream fstream = new FileInputStream("src\main\resources\ids.txt");
how to reference the properly from the classpath?
EDIT
When I edit my code according to @BalusC solution , here is how it looks but I still get null
error :
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("src/main/resources/ids.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String strLine;
while ((strLine = br.readLine()) != null) {
....
....
.....
end while
end method
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…