4

Files are no longer readable

 2 years ago
source link: https://www.codesd.com/item/files-are-no-longer-readable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Files are no longer readable

advertisements

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK