I am using Intelli-J Idea IDE and working on a Java EE Web project. I am trying to read words.txt
file. The code is working fine in command line, but when I deploy the code into glassfish server it gives me "FileNotFoundException".
File is located in "src/Analyser/pWords.txt"
Code to read the file content:
Scanner scan = new Scanner(new File("src/Analyser/pWords.txt"));
After searching StackOverflow, I found out that I need to add this file to resources directory. Unfortunately, I am unable to create resources. When I create the package main
and the resources in the src
folder, the package becomes main.resources
, I tried another way such as:
InputStream inputStream = new FileInputStream("src/Analyser/pWords.txt");
AND
InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream("src/Analyser/pWords.txt");
InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream("pWords.txt");
But the result is null
or error
.
So is there any way I can read the file from src/Analyser/
directory in my project? It's a Java EE Web project.
UPDATE:
From the Project Structure > Artifacts > WEB-INF
folder, I uploaded the pWords.txt
file. and Now finally, BufferedReader is not empty, while debugging I can see that bufferedReader
contains data. But when I copy the data to a string variable, the variable remains null. I am quite confused about it.
Code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("pWords.txt");
BufferedReader bf = new BufferedReader(new InputStreamReader(stream));
String t = "";
try {
while((t = bf.readLine()) != null) { // in debugging, (cb) contains the char data as char elements.
t += bf.readLine(); // but t = null
}
} catch(IOException x) {
}