0

I have the following project structure: Project Structure. I need to read and write data to that input.xlsx file for my program. Opening the file as the following:

code

, it works fine inside NetBeans, the problem is when I build it as a .jar file, the project structure is not kept. What are the steps I should follow?

dan1st
  • 12,568
  • 8
  • 34
  • 67

1 Answers1

1

careful: Lots of wrong answers in the comments.

getResourceAsStream is a good answer, but it is not used in the way the comments suggest. The right answer is this:

ClassThatYourReadDataFromXlsxMethodIsIn.class.getResourceAsStream("/input.xlsx");

Note: there's a slash in there. That is not a typo; your file (input.xlsx) is relative to the src/main/resources directory in the 'root'. Had it been in a subdir named MyPackage (matching the package of ClassThatYourReadData class is in), then you can omit the slash.

This gives you an InputStream. Note that you cannot cast this to a FileInputStream - the point of gRAS is to get you the files from the same place your class files lives, and that is usually not a file at all - entries in jar files are not themselves files.

Fortunately, you don't have to write that cast - XSSFWorkbook works fine if you feed it any old InputStream, there is no need whatsoever to involve files in this.

Maven should automatically bundle the file into the jar. Give it a test! If you ask maven to build you a full distro, is input.xslx in that jar? You can check out the contents of a jar with: jar tvf yourjar.jar.

"src/main/resources" should not be anywhere in your source code - it looks like that at build time. It doesn't look like that at runtime/production; why would there be a 'src' directory at all?

You cannot write files inside jars in any case.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Works like a charm! I wonder how can I open the same file using "Desktop.getDesktop().open(file)" ? – Remus Bulboaca Jul 28 '20 at 17:41
  • You can't; Desktop.getDesktop().open can only open files. You'd have to 'unpack' your resource into some directory and then open _that_. For example, something like (add appropriate try-with-resources protections, of course): InputStream in = YourClass.class.getResourceAsStream("/input.xlsx"); File f = new File(System.getProperty("user.home"), "foo.xlsx"); OutputStream out = new FileOutputStream(f); in.transferTo(out); [end try-with-here] Desktop.getd..open(f); – rzwitserloot Jul 28 '20 at 21:43