Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading from JAR files during deployment vs development

when i am loading some data into my java program, i usually use FileInputStream. however i deploy the program as a jar file and webstart, so i have to use getRessource() or getRessourceAsStream() to load the data directly from the jar file.

now it is quite annoying to always switch this code between development and deployment?

is there a way autmate this? i.e. is there a way to know if the code is run from a jar or not?

when i try to load it withoug jar like this:

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

the returned inputstream is simply null, although the file is definitely in the root directory of the application.

thanks!

like image 814
clamp Avatar asked Nov 20 '25 02:11

clamp


1 Answers

Why do you use FileInputStream during development? Why not just use getResourceAsStream from the very start? So long as you place your files in an appropriate place in your classpath, you shouldn't have any problems. It can still be a file in the local filesystem rather than in a jar file.

It's helpful to develop with the final deployment environment in mind.

EDIT: If you want something in the root directory of your classpath, you should either use:

InputStream x = getClass().getResourceAsStream("/file.txt");

or

InputStream x = getClass().getClassLoader().getResourceAsStream("file.txt");

Basically Class.getResourceAsStream will resolve relative resources to the package containing the class; ClassLoader.getResourceAsStream resolves everything relative to the "root" package.

like image 52
Jon Skeet Avatar answered Nov 22 '25 16:11

Jon Skeet