0

My problem is a bit different from the ones that are there in SO...I will try to explain..

My code pick up an .xls file from a location (c:\codereview\) and inserts data into that file. I was using full file path for this but realized my program is not portable.

So I copied my xls from c:/ drive into the src/ folder and I now I keep getting a FileNotFoundException.

FileInputStream file = new FileInputStream(new File("/src/New_Record.xls"));

HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);

when i try to use:

FileInputStream file = (FileInputStream) Util.class.getResourceAsStream("New_Record.xls");


i get below exception:

java.lang.NullPointerException at org.apache.poi.poifs.filesystem.POIFSFileSystem.closeInputStream(POIFSFileSystem.java:183) at org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:145) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:322) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:303)

Basically I want to use a combination of FileInputStream and InputStream so that i can use that with HSSFWorkbook. InputStream is not compatible directly with it and FileInputStream is not compatible with this.getClass.getResourceStream.

vaibhav misra
  • 135
  • 6
  • 19
  • Try to remove the leading `/`. – stevecross Jul 16 '14 at 10:41
  • Have a look at the absolute file path in debugging mode, you can spot the error there. – Tobias Jul 16 '14 at 10:43
  • Add a `resources/` folder in your `src/` folder. Then use the `ClassLoader.getResource()` method to load the resource. Also make sure that the file exists in your classpath. – Mr. Polywhirl Jul 16 '14 at 10:43
  • Please post the exact error you're getting, it would be very helpful. – CupawnTae Jul 16 '14 at 10:45
  • 1
    Your classpath will start from the directory above source so I would try src/New_Record.xls – JamesB Jul 16 '14 at 11:04
  • @Mr.Polywhirl...your suggestion worked for me...i used getClassLoader.getResource("New-Record.xls") and it returned me the path of the file. – vaibhav misra Jul 16 '14 at 18:14
  • @Mr.Polywhirl... i used 'URL stream = ClassName.class.getClassLoader.getResource("New-Record.xls")' and it returned me the path of the file. I then converted the variable stream to string and used it with FileInputStream as mentioned in original question and my issue got resolved...thanks a ton for the suggestion..i had one more doubt: When i print the path of the file it gives a temp location and not the /src/New_Record.xls location as i was expecting...C:/*/workspace/.metadata/.plugins/org.eclipse.core/tmp1/wtpwebapps/PLT/WEB-INF/classes/New_Record.xls is what is returned...any guesses why? – vaibhav misra Jul 16 '14 at 18:22

0 Answers0