tags:

views:

90

answers:

2

I need to ship some Java code that has an associated set of data. It's a simulator for a device, and I want to be able to include all of the data used for the simulated records in the one .JAR file. In this case, each simulated record contains four fields (calling party, called party, start of call, call duration).

What's the best way to do that? I've gone down the path of generating the data as Java statements, but IntelliJ doesn't seem particularly happy dealing with a 100,000 line Java source file!

Is there a smarter way to do this?

In the C#/.NET world I'd create the data as a separate file, embed it in the assembly as a resource, and then use reflection to pull that out at runtime and access it. I'm unsure of what the appropriate analogy is in the Java world.

FWIW, Java 1.6, shipping for Solaris.

+6  A: 

It is perfectly OK to include static resource files in the JAR. This is commonly done with properties files. You can access the resource with the following:

  Class.getResourceAsStream ("/some/pkg/resource.properties");

Where / is relative to the root of the classpath.

This article deals with the subject Smartly load your properties.

Kris
+1 for properties file
Jeremy
Works perfectly. Thanks!I embedded my data file as a property file, then used `getResourceAsStream` to get a handle to it. From there, `InputStreamReader` and finally `BufferedReader` gave me a simple way of using `readLine()` on my embedded data file. Perfect.
Andrew
+2  A: 

Sure, just include them in your jar and do

InputStream is = this.getClass().getClassLoader().getResourceAsStream("file.name");

If you put them under some folders, like "data" then just do

InputStream is = this.getClass().getClassLoader().getResourceAsStream("data/file.name");
Enno Shioji