Question

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!

Was it helpful?

Solution

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 an InputStream.

Example:

reader = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/FileFolder/MyFile.txt")));

Edit: If this is from a Servlet, consider using gawi's answer instead.

Edit 2: If this is in a static method, you'll need to use MyClass.class instead of this.getClass(), where MyClass is the class name.

OTHER TIPS

You are opening a file using a path relative to the current working directory. That's not likely to work on a web app container because the current working directory will not be the root of your application.

Furthermore, you file might not be on the file system but rather in a WAR file.

The proper way to open a file in a webapp is to use the ServletContext.getResourceAsStream() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top