如何在 .jar 文件中包含 .xlsx 文件?

huangapple go评论84阅读模式
英文:

How to include .xlsx files inside .jar?

问题

我有以下的项目结构:如何在 .jar 文件中包含 .xlsx 文件?
我需要为我的程序读写那个 input.xlsx 文件。
按以下方式打开文件:

如何在 .jar 文件中包含 .xlsx 文件?

在 NetBeans 内部运行时,它在正常工作,但当我将其构建为 .jar 文件时,项目结构未被保留。
我应该遵循哪些步骤?

英文:

I have the following project structure: 如何在 .jar 文件中包含 .xlsx 文件?.
I need to read and write data to that input.xlsx file for my program.
Opening the file as the following:

如何在 .jar 文件中包含 .xlsx 文件?

, 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?

答案1

得分: 1

注意:评论中有很多错误的答案。

getResourceAsStream是一个好的答案,但它的使用方式不同于评论中所暗示的。正确的答案如下:

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

注意:路径中有一个斜杠。这不是拼写错误;你的文件(input.xlsx)相对于根目录的src/main/resources目录。如果它在名为MyPackage的子目录中(与ClassThatYourReadData类所在的包相匹配),那么你可以省略斜杠。

这将为你提供一个InputStream。请注意,你不能将其强制转换为FileInputStream - gRAS的目的是从与你的类文件相同的位置获取文件,这通常不是一个真正的文件 - jar文件中的条目本身不是文件

幸运的是,你不必编写这个转换 - 如果你将任何旧的InputStream提供给XSSFWorkbook,它也能正常工作,根本没有必要涉及文件。

Maven应该会自动将文件捆绑到jar中。试一下吧!如果你要求Maven为你构建一个完整的分发版本,input.xlsx会在jar包中吗?你可以使用以下命令查看jar的内容:jar tvf yourjar.jar

在你的源代码中不应该出现"src/main/resources",它只是在构建时才是这样。在运行时/生产环境中,它看起来并不是这样;为什么会有一个src目录呢?

无论如何,在jar中都不能写入文件。

英文:

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.

huangapple
  • 本文由 发表于 2020年7月29日 00:30:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63138737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定