Skip to main content

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 @!


Comments

  1. 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:


    http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)


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


    In Java, how do I read/convert an InputStream to a String?

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

Java Urban Myths

Along the line of C++ Urban Myths and Perl Myths : What are the Java Urban Myths? That is, the ideas and conceptions about Java that are common but have no actual roots in reality . As a Java programmer, what ideas held by your fellow Java programmers have you had to disprove so often that you've come to believe they all learned at the feet of the same drunk old story-teller? Ideally, you would express these myths in a single sentence, and include an explanation of why they are false.