Access properties file in an executable jar [duplicate] - java

This question already has answers here:
Reading a resource file from within jar
(15 answers)
Closed 6 years ago.
My goal is to create an executable jar from Eclipse. I have an Eclipse project which runs fine with the structure below.
My Eclipse project
src/main/java
-com.main
->MyClass
src/main/resources
->MyProps.properties
MyClass is able to access MyProps.properties file successfully.
After I export the Eclipse project and create a runnable jar then my jar structure is like below.
MyJar.jar
-com.main
->MyClass
-resources
->MyProps.properties
When I run the jar file it fails to access the properties file throwing a NullPointerExeception.
My code
InputStream input = MyClass.class.getClassLoader()
.getResourceAsStream("resources/MyProps.properties");
When I export my project as an executable jar file, I cannot access MyProps.properties anymore.
Can someone help me please?

You can use code like below to read a properties file on the Class Path:
MyClass.class.getClassLoader().getResourceAsStream("MyProps.properties")

In onder to load a file from a jar. You have to use Class.getResource() or Class.getResourceAsStream().
URL properties = ConfigLoaderTest.class.getResource("/resources/MyProps.properties");
This will load the file from your classpath, this means it will also look inside the jars on your classpath (the executable jar is on your classpath automatically). The first '/' indicates to look from the root of the jars on your classpath, you have omitted this in your code.
The URL you can then read like any URL (it will return null if none is found). For instant by using properties.openStream().
Note that it seems you are using the default maven structure src/main/resources, however you have src/main on your eclipse buildpath, so in your jar you get the resources directory. Normal for maven projects is to have src/main/resources on your buildpath. Which would place your properties file in the root of your jar.

Related

Could not read config file: No such file or directory: src/main/resources/floodlightdefault.properties

I am working with the Floodlight SDN controller, which is a Maven project.
I am trying to run a.jar file that I got by using the maven package command.
when I try to run the jar using java -jar floodlight.jar, I get this error:
ERROR [n.f.core.Main] Could not read config file: No such file or
directory: src/main/resources/floodlightdefault.properties
The problem is that the application looks for floodlightdefault.properties using an absolute path:
src/main/resources/floodlightdefault.properties
This path does not exist in the jar, but the file itself exists (in the root).
What I have done so far:
I confirmed that this is the source of the problem by moving the jar to the correct directory in relation to the absolute path, and it ran from there.
My Question:
How can I build this Maven project so that it does not use absolute path with the jar? the project's codebase is large and I do not know where this file is being called. but I think the error is on me as I am a beginner.

How do I package this maven project or Java Application?

I'm creating a new project that run as a Java application(.jar), but I am confused about how to package the lib folder into the final jar file.
And I try to use Maven, but did not found some eligable plugins.
The project structure is here
first, I try to package with IDEA's build Artifact. it will extract all jar file into final jar and create a MANIFEST file, but the impact is there are some file like "*.SF, *.RSA", it destory the java -jar xxx.jar, But we can solve it by delete these .sf/.rsa file. Next problem occur, cause I use some springframework dependency, when extract these jar file, they will create a file like spring.handles, but its not complete.
second, I try to use MAVEN. I use the maven-jar-plugin maven-compiler-plugin maven-dependency-plugin to copy all jar file into final jar, and create the correct MANIFEST file. BUT a java.lang.NoClassDefFoundError occur, I am DEAD!!!
So, the actual question is how can I package the lib folder into final executable jar???

Java export running jar w/ project

So, I've added a git repo to my project (sjxlsx). I've then right-clicked the repo and imported into the package explorer. I then went to Project->Build path in order to make sure it's on "Required projects on the build path".
When I debug on Eclipse, works just fine.
I'm now trying to export as a running jar and when I execute it outside of Eclipse, it somehow is giving an error (empty.xlsx not found). That is, because in the XLSXWriterSupport, the open method is fetching this empty.xlsx file. On debug, it's working as expected but on converting to a running jar, it's giving me this error.
This is due to this 'empty.xlsx' file being on the resources of the other project. How can I solve this?
https://github.com/davidpelfree/sjxlsx/blob/master/src/main/java/com/incesoft/tools/excel/support/XLSXWriterSupport.java
This is because a resource on the class path is not a File on the file system.
Here it is packed in a jar (zip format).
The wrong code:
if (getClass().getResource("/empty.xlsx") == null) {
throw new IllegalStateException("no empty.xlsx found in classpath");
}
workbook = new SimpleXLSXWorkbook(new File(getClass().getResource("/empty.xlsx").getFile()));
As SimpleXLSXWorkbook has only a File constructor (AFAIK), you need to create a temporary file.
Path tempPath = Files.createTempFile("sjxlsx-", ".xlsx");
Files.copy(getClass().getResourceAsStream("/empty.xlsx"), tempPath);
workbook = new SimpleXLSXWorkbook(tempPath.toFile());
Better have some provision to delete temp files, for instance creating them in a specific directory, see Files.
You probably have the Eclipse Project build path configured to use absolute library references. When you try to run your runnable jar, the jvm cannot find the required dependencies.
Edit:
If you want to export your software as a RUNNABLE jar file, then the jar must contain a MANIFEST file which specifies the dependencies and main class. Example:
Manifest-Version: 1.0
Main-Class: com.example.Main
Class-Path: lib1.jar lib2.jar
(assuming your main class is com.example.Main)
In order to run your runnable jar file, place lib1 and lib2 on the same directory as your runnable jar and run:
java -jar myJar.jar
Otherwise you could just compile your main class and run it like this (assuming lib1 and lib2 are copied into a lib/ dir on your main class root path):
java -cp '.:/libs/*.jar' com.example.Main
You could also use a dependency manager tool such as maven and configure your build to create an "uberJar":https://maven.apache.org/plugins/maven-shade-plugin/examples/includes-excludes.html
uberJars contain all your software dependencies in one heavy runnable jar file.
Hope this helps.

Jar file when extracted and rebuilt, isn't working

I'll try to be clear and concise on this.
i have a jar file of a project which is working perfectly. Now I need to make some changes to the application so i extracted that jar using this command.
jar xf jwire.jar
the files extracted are
META-INF (containing manifest file)
Resources (containing pictures used in application)
Jwire (containg classes and java files)
.classpath
.project
manifest.mf (another manifest file with some other path to main class)
i also added two empty folders src and bin here on somebodys suggestion.
now i'm trying to create the jar file again using all these folders.
Without making any type of changes I'm trying to rebuild this jar using the following
jar cf newjar.jar G:\Project1\project
NOTE:- I am guessing it's the right way to build the file. Please point if it's not right.
G:\Project1\project is the path to above mentioned files and folders.
The jar created using this is of size 729kb while the earlier one had 711Kb and when I run it using the following command.
java -jar newjwire.jar
I get the following message
no main manifest attribute, in newjwire.jar
Next i tried extracting this newjwire.jar file in order to see its manifest file. I got this folder META-INF containing the MANIFEST.MF file. it didn't have the path to the main class , So I edited it and put the modified file back on using the following command
jar uf newjwire.jar META-INF/MANIFEST.MF
when I run this jar, I get the following message
Error: Ivalid or corrupt jarfile newjwire.jar
What am I doing wrong? Am I building the jar file the right way? I used eclipse juno too and it gave the same message to that mainclass is missing. There is a main class consisting the main function. Is this something has to do with My orignal jar having two MANIFEST file.
I hope the problem is understandable. Clear and detailed answers will be appreciated.
you're supposed to update JAR files by jar uf jar-file input-file(s)
see this link: http://docs.oracle.com/javase/tutorial/deployment/jar/update.html
According to this page you need to EITHER have Manifest.txt present when you create or update the JAR, or use the e option to specify the main class. Probably the latter would make more sense in your case.
jar cfe newjar.jar mypackage.MainClass G:\Project1\project

executable jar file not running outside of the folder where I created it

I created a jar file in my working folder
jar -cfe MRMC.jar MRMC *.class *.jar DB statpack
and I am able to double click the jar file or run it using
java -jar MRMC.jar
But when I copy the jar file to another location, I can no longer run it. I got errors:
Exception in thread "main" java.lang.NullPointerExeption
it seems that the jar file did not find files in the resource folder DB above.
Thank you.
I see two possible reasons:
a) the content of the DB directory does not end up in the jar. Unzip the jar to check what is actually inside. Note: a jar is just a zipfile.
b) you are not referencing the files as a classpath resource, but as a File Resource. Check the methods you are using, if they are based on the classpath or on the file system.
See this question for the different ways to load a file: How should I load files into my Java application?

Categories