Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

java - How to read jrxml file inside the jar file?

I have a bunch of iReport source code (jrxml) locate inside the workspace with the following path:

<project>/report/<jrxml_file>

When I pack my source code into jar file. I will have this file structure directory:

<jar_file>/report/<jrxml_file>

In my source code, I have these code to validate the existence of the jrxml file:

File file = new File("report/jrxml_file");
if (!file.exists()) {
   return false;
}

When I execute this jar file through the command:

java -jar MyJar.jar

I hit an error mention that the particular jrxml_file doesn't exists.

My doubt:

  1. I am just curious to know whether am I allow to read the jrxml_file which is locate inside MyJar.jar?
  2. Do I need to extract the jrxml_file to a physical directory before I can read it?

THanks @!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the file is on top of your jar at given path, you can use this:

InputStream is = this.getClass().getResourceAsStream("/report/jrxml_file");

See Java Class docs:

From there, you can read it as any other InputStream, for example using Apache IOUtils, as explained here:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...