kevin ternet kevin ternet - 28 days ago 6
Java Question

How my bean can read a file

I' need help to open a file using Eclipse. indeed, I don't know where to locate my file in Eclipse file tree to avoid raising this exception :


**java.io.FileNotFoundException: wages.xls **
at this line :
FileInputStream file = new FileInputStream("wages.xls");
.

Answer

You need to add this file to a folder located in your classpath, usually named resources. You can then access the content of this file through the Classloader of your classes :

class Test {
    public static void main(String[] args) {
        InputStream myFileContent = Test.class.getResourceAsStream("/directory/file");
    }
}

This would work with a project with the following file tree :

  • projectRoot
    • src
      • Test.java
    • resources
      • directory
        • file

And a classpath including both the src and resources directories.