1

I have a JSF application with the below file structure:

ReportGeneratorJSF
 |-- src
 |    `-- Abc.java
 |-- WebContent
 |    `-- FormattedExcel
 |         `-- abc.xls
 :

In my Abc class I need to refer the Excel file as

File file = new File("location of abc.xls");

However, whatever path I try, it comes as null. How do I figure out the right path?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Soheb
  • 93
  • 2
  • 12

1 Answers1

3

The java.io.File works directly on local disk file system and has absolutely no utter idea about the Java (EE) application context it is running on. So it does absolutely not know that the application "root" is located in C:/some/path/to/ReportGeneratorJSF. It would assume every relative path to be relative to the "Current Working Directory", i.e. the directory which was currently opened when the Java Virtual Machine is started.

You should never rely on relative paths in java.io.File being treated correctly. Period.

Given that you've saved it as a JSF webapp resource in the project's webcontent folder, you should instead be using ExternalContext#getResourceAsStream() to get an InputStream out of it (ultimately, you'd like to create a FileInputStream out of the File, right? How else would the File be useful?). It takes a path relative to the webcontent root instead of the disk file system's current working directory.

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = ec.getResourceAsStream("/FormattedExcel/abc.xls");
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555