I have a Java project which has this file structure (shown in Eclipse):
ProjectName
+- Deployment Descriptor: ProjectName
¦- Java Resources:src
¦- Package1
-MyClass.java
¦- FileFolder
-MyFile.txt
And so far from myClass I’m able to read MyFile.txt using:
try
{
reader = new BufferedReader(new FileReader(new File("FileFolder/MyFile.txt")));
while((line=reader.readLine())!=null)
{
line=line.trim();
myVector.add(line);
}
reader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
But when I put Package1 into a Dynamic Web Project AND the FileFolder folder in root, the file is no longer found.
Does anyone know how to read the file?
Thanks in advance!
Dynamic Web Projects generate WAR files.
The server may or may not expand the WAR file back to a file system structure.
You’re best off using the Class or ClassLoader
.getResourceAsStream("/FileFolder/MyFile.txt")which can read files from JAR/WAR files, and returns anInputStream.Example:
Edit: If this is from a
Servlet, consider using gawi’s answer instead.Edit 2: If this is in a
staticmethod, you’ll need to useMyClass.classinstead ofthis.getClass(), whereMyClassis the class name.