cannot find or load main class when run a jar - java

Firstly, I know this problem is asked frequently. But My problem is different, so please be patient to see the full description.
I have utilized intellij IDEA 2018.2 to build the jar. I have ever built the jar with 2017 and it worked fine. Recently, I have used intellij to build the jar with artifact.
And the setting seems to be fine. It worked for me before. But I ran the built jar, it indicated that "the main class cannot be run or loaded".
The jar file seems normal. But I found the META-INF is different. I have some files are strange:
I find if I delete these files except MANIFEST.MF. It can work fine. I am not sure what's the difference of the settings.
I have tried the below methods:
Try to delete the .idea folder, and open the project.
Try to remove the artifact and configure a new one.
Try to modify the output path of module.
Rebuild the project or rebuild the artifact jar.
But all the methods cannot work. And I have tried to build the jar with the same settings in both MAC OS and windows OS in intellij, but the result seem to be same. Can any one provide me with some suggestions. Thank you in advance.

The *,RSA, *.SF, *.DSA are files that are created when the jarfile is signed. Apparently, the jars that you use are signed and so if you extract the contents and place them in a new jar, the signature is invalid and Java won't accept them. So you should either remove the signatures, or resign the entire jar that your artifact produces.

I have found that what is solution for this. I should not import the dependencies as a folder. I have to import them by select all the jar files instead of the folder of the jar files.

Related

Folders can not be found after converting a JAVA project into a runnable JAR

I hope somebody can help me with my problem. After hours of scanning all different posts concerning the abovementioned topic I now decided to answer my own question. None of the other posts solved my problem.
I want to export an existing JAVA project as runnable JAR. Therefore I'm changing all absolute references to the following:
this.getClass().getResource("/somekindofimage.png").toString();
This way I can reach all available files in the runnable JAR.
However I need to reference a folder...so I tried it the same way:
this.getClass().getResource("/somekindoffolder").toString();
which gives me the following path:
file:\C:\Users\...\1_data_collection
By creating a file and checking with "is.Directory" it returns false.
I unzipped the runnable JAR. All folders, all files that are needed are included. They are attached as sources via BuildPath.
When I test the abovementioned path with Windows Explorer it directs me to the folder I'm looking for.
I'm using Eclipse Neon 2 as IDE, my JAVA Version is 1.8-0_144.
Thanks in advance!
You can't refer to files in a JAR using a File path. You have to load them as resources from the classpath.
Make sure the resources and dependencies you need are packaged in the JAR. There's a Maven Shade plugin, if you're using Maven, that will do it for you.

java.lang.ClassNotFoundException when running in IntelliJ IDEA

I creating a program to work with databases and I am getting the following error when compiling in IntelliJ IDEA. Does anyone why this is happening and how I could solve it?
The error that you get occurs not on complilation, but when you try to run your application. It happens because Java was not able to find Table.class file inside db subdirectory of the project output directory (classpath).
It can happen for multiple reasons:
wrong main class selected in the run/debug configuration
Table.java is excluded from compilation (by accident or intentionally because it contained errors and you wanted to skip it while working on other code)
class not compiled because Build step is excluded from from Before launch steps in the Run/Debug configuration
project is misconfigured and there is no Source root defined for the directory containing db subdirectory
Table.java has incorrect package statement or is located/moved to a different package
project path contains a colon : on Mac/Linux or semicolon ; on Windows, it's used to separate the classpath and will render the classpath invalid. See this thread for details. Note that Finder on Mac may display colons in the path as slashes.
the jar may not execute if one of the dependent jars is digitally signed since the new artifact will include the partial signature of the dependency. See this answer for more details.
In project structure make sure you have the right Java version for compile.
there is a known bug that sometimes a Java project created from the Command Line template doesn't work because .idea/modules.xml file references invalid module file named untitled104.iml. Fix the module name manually or create a project from scratch and don't use a template.
on Windows "Beta: Use Unicode UTF-8 for worldwide language support" Region Setting is enabled. See IDEA-247837 for more details and workarounds.
When IntelliJ IDEA is configured to store module dependencies in Eclipse format source root configuration is lost due to a known bug. Configure the module to use IntelliJ IDEA format dependencies as a workaround.
In a properly configured project and with the correct run/debug configuration everything works just fine:
the jar may not execute if one of the dependent jars is digitally signed since the new artifact will include the partial signature of the dependency. See this answer for more details.
I must again emphasis the point CrazyCoder has here.
The (Oracle) JVM used to throw a SecurityException when you tried to run a Jar-File containing broken signatures. This made sense from a "What's wrong"-Point of view.
That is no longer the case. They are indeed throwing ClassNotFoundExceptions now - even if the class is right there in the file (no matter if it is in the default package/toplevel or way down in a nested package structure).
Here's what worked for me:
I deleted .ide folder, .iml file. And all other auto generated files by intelliJ then restarted my ide and I was asked if I want to make my project run with maven that's it.
Obviously I said yes :)
This is a known bug in the IntelliJ idea.
To fix this I just deleted the .iml and the .idea and restart the IDE.
It works for most of the cases
Edit: The files will be in the project directories.
In my case the default console app template works only if the project folder path does not contain underscore (_) in it. Underscore brings the error
Error: Could not find or load main class com.company.Main
Caused by: java.lang.ClassNotFoundException: com.company.Main
IntelliJ IDEA 2021.3.1 (Ultimate Edition)
Build #IU-213.6461.79, built on December 28, 2021
If you've tried everything else that others have suggested (deleting .idea folder, rebuild, etc) there's another place to check, especially if you've built an artifact jar. When you first build an artifact jar, IntelliJ adds a folder: META-INF to src directory. in it is a single file: MANIFEST.MF which has info pointing to the Main-Class for Java to find. If you've refactored your project package, unfortunately IntelliJ does not update this file with the new changes. My MANIFEST.MF has the following correct content:
Manifest-Version: 1.0
Main-Class: org.umoja4life.fatashibackend.MainKt
Where "org.umoja4life.fatashibackend" is the package name, and "MainKt" is IntelliJ's constructed name for a (pseudo) "Main Class" because fun main() has been defined in file "main.kt" in the package directory.
Newbies: btw, This will be confusing for you because there should be no actual "class Main {}" definition despite the error message stating there should be.
Before I discovered this file and after trying everyone else's suggestions, I found it quickest to just have IntelliJ start a project (with correct package name!), initialize it with a trivial main.kt having:
fun main() { println("hello world!") }
run and test that; then, I added back in all my other files, rebuilt, ran, and tested it. Apparently IntelliJ has some secret state information stored somewhere which doesn't get correctly updated if your refactor your package name for an already running project and jar.

Eclipse doesn't compile java files into classes

I have no idea why, but from today Eclipse doesn't compile .java files into .class. I press the "Run" button and Eclipse only tries to run the program rather then compiles it first, so i get this error all the time:
Exception in thread "main" java.lang.NoClassDefFoundError
open problems view from window -> show view -> problems, if there's any error, fix it
eclipse will reject to compile if there is any problems in your project
Close Project -> Open Project -> Clean -> Refresh
Hope it helps for someone else
This problem happens when "for some reasons" your project is corrupted and has a red icon near the project's name in Eclipse. The solution is to save the project's folder, delete the project in Eclipse, than create the project again in Eclipse coping all the previous files saved.
I ran into this problem with Eclipse Luna, for some reason the Java builder was missing from the project. Verify that in your .project file you have something like
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
You can also configure builders from Project Properties -> Builders
When I have had this exact same problem, its cause has always been the same and the solution has worked 100% of the time for me. It's caused by a missing jar file in the project's Java build path and it's indicated by a red exclamation point decoration on the project icon. To fix the problem, go to Project|Properties|Java Build Path, click on the Libraries tab and either remove or fix the path for all missing jar files. If your project is configured to rebuild automatically, it should start a build as soon as you apply your changes.
The eclipse needs to erase the output folder when building classes.
The folder is found on Project Properties -> Java Build Path -> Default Output Folder. It can differ from general output folder name found under Eclipse Preferences. If this output folder cannot be erased for some reason (for instance, on Windows, when a shell is opened on this location), the project is marked as corrupted (as Marco Micheli describes) and the classes then are not built.
You just need to make sure the output folder can be erased.
Yes I was facing this issue. Coz Eclipse cannot build the project for Build Path error. Check that your external jar files is not showing any error. Delete the Jar file which one is missing or which one is showing re color. delete that one. add a fresh one from the correct path or location. if all the error are gone. then in the project bin folder one class file will be created and then could not load main class error will be removed too.
there can be errors in your project, or other reasons like mentioned in above answers.
or you may be a fool like me
who moved the source code to other folder and not updated source path in project build properties. in this case it was not giving any error or class files too.
check that too.
goto
Project Properties -> Java Build Path -> Source
Add or Link new source folder location.
Do clean all projects ! This will erase all old class files, so eclipse is forced to generate them again.
Some times jars in the build path might be missing even though we are not using it. Since error is there, java files wont compile into classes.
Can check errors from problems view.
Either remove jars from build path or place the missing jars in the build path.
I had problem in eclipse for load module not found and no class file was getting created.
Solution: Go to Create New Project > Under JRE section Choose Use project Specific JRE.
Now Class files are created.
Please check if all the jars are there in your build path settings.
If any jar is missing this issue might come.
I had this problem, I tried the clean, the build manually, open, closing the project, deleting, and open, etc., nothing works, and after 4 hours I get a workaround what works for me.
Please, Make a RAR, ZIP, or copy from your entire project folder as a backup if it doesn't work and you mess around, OK, now:
Clean the Project. It cleaned all my class files from the output folder, but doesn't generate the class files after the clean with the building (but we already know that)
Delete the project (warning, make sure the Delete contents is not selected or your project will dissapear). For me it says something about that desynchronysation with code mix, and hibernate, blabla)
Close myEclipse
Restart your computer.
Open myEclipse
Import the project with the option "Projects from folder or Archive", not with the "existing projects into workspace" option.
Myeclipse start to build the class files, I don't know why, but works for me, I hope this helps somebody else.
Also ensure that there are no projects with fatal errors (projects with ! symbol over it) in the build path of the project which is not generating classes under the bin directory
Just restart your machine.
Its weird but it helps we had loads of problems this type in our company for unknown yet reason. Always restarting the machine helped.
It was normally encountered while trying to run Junit tests and it could not find a class even when the Run configuration was pointed to /bin.
I encountered a similar problem: previously compiled and running java files couldn't run anymore. Eclipse showed "couldn't find class xxxx". When I checked bin folder, the previous .class files were gone. That's why Eclipse couldn't run the files, NOT because of errors in files. I don't know why it can't just re-compile the file, and why the .class file gone missing in the first place.
But I found a solution:
Simply create a dummy java file in the same package (without doing anything just create), then run it. Then magically all previous .class files came back. And I can run those files as before.
Just Remove Your all Jars (Libraries) from the Build Path and refresh and add all jars and clean and build the project
This is probably a rare event but I declared a servlet with annotations and left off the "/" before the servlet mapping name. I spent over an hour chasing my tail, installing new servers, thinking I might even need to re-install my IDE and it was this simple error! Every time I tried to load any page from my Dynamic Web Project I got a 404 error. I could not even load a plain vanilla html page. There really needs to be better error logging with the IDE and Server interaction as there was zero indication of the error and my servlet was never called at the start of my web app. Hope this helps save someone else some frustration. Always name your servlet with a / slash like /myServlet never just myServlet.
I tried many different potential solutions: cleaning, rebuilding, removing, re importing, Update Maven Project and nothing. I still couldn't run my app from Eclipse. In my case the reason was that I was running Eclipse using openjdk-11 while my project was in Java 8. After I've reconfigured Eclipse to be ran from Java 8 everything started to work (in eclipse.ini).
-vm
/usr/lib/jvm/jdk1.8.0_202/bin
I'll explain my solution to this problem: "eclipse not compiling java files into class files". I'm using Eclipse version '2020-03 (4.15.0)'. I have a project that is dependent on a java project. For the dependent project, I was not able to export a jar file containing the compiles classes and resources. To be more precise, the exported jar file did not contain any class files. The output bin folder for the project is empty after doing a project build. In examining the console output when I tried to build all projects indicated that the build failed because the dependent project was missing. In looking at one of the log outputs, I saw something indicating that the build failed because some eclipse class was missing.
One of the things I tried was to do an eclipse update. Eclipse offered up the list of changes and I tried to apply them, but the update failed. I tried to update several times but they all failed. Looking more carefully at the offered up list of updates I noticed that one of the suggested update involved "deleting" Java Development Tools. That line had an warning indicating that the entire feature could not be deleted due to other dependencies and that only the non dependent features would be deleted. Doesn't that sound suspicious. Why was the update trying to delete Java Development Tools? My speculation is that something got deleted from the Java Development tool that was causing the build process to fail. The missing class I saw earlier also suspiciously sounds like it might be part of the Java Development Tools feature.
So what I did to solve the problem was to reinstall eclipse. I used the eclipse loader application to do the reinstall. (Note, I did not uninstall it first). After the reinstall, the dependent project was able to produce classes, and things once again worked as they should.
I certainly don't know how the eclipse release got into this compromised state, but in my situation the re-install of eclipse was the only way I could find to resolve the problem.
There would be the case : if you have opened project explorer in eclipse then it may not show you classes generated under /**/build/classes, in such case open Navigator view of that project and check build directory under the same project.

Eclipse cannot create runnable jar - No resources selected

When I try to export my project as a runnable jar Eclise gives me the following error:
No resources selected.
The project runs fine within Eclipse, I already tried to clean the project before exporting, but that didnĀ“t work.
Any ideas on how to fix this.
The problem is most likely with your run configuration.
Go to your Class that contains the main(String[] args) method you wish to automatically run
when the jar is called from the command line
Right-click->Run As...->Application
Make sure it runs to your satisfaction
Now go through the export process as before, selecting the newly created launch configuration.
The last step is key.
I found another solution.
I found that there's a bug in JDK 9.
I solved it by downgrade to JDK 8(1.8.1)
I fixed the problem, I exported the project as an archive file. Then I opened up a new workspace and imported the the archived project. After that I tried to export the project as a runnable jar, after two tries the jar runs as is it should.
I still don't know what the exact cause was but I hope someone how has run into the same problem finds this helpful.
Doing a (project->clean) and creating a new run configuration (with correct project and class name with main() method, selected) solved the problem for me.You just have to select the new run configuration while exporting runnable jar :)
Try this, this is the way to create a jar or runnable jar in eclipse, all your external libraries in the project will be included
File -> Export-> Java ->Runnbale JAR file
Launch configuration : your Class containing the public static void main(String[] args)
Export destination : Target place
Library Handling:
Package required libraries into generated JAR
FINISH
When you click this option in Eclipse you should get a popup that lets you choose what files to export, you need to select the src folder.
I was having this same problem, and I was able to resolve it. Maybe you should cross verify the main class, that you selected in this project. It is possible that some other project's main class may have the same name as the main class you selected. Make sure the main class you selected is the one from the project that you selected.
The problem is your package. You probably renamed it, and in the export option, the program was confused, and it was using the first name of your package.
This is basically happen when you change package name under which you made your program. This will create confusion regarding package, as per program export, main method still written in old package.
To resolve it, Just copy it and paste it in same package with different name and then try to export it. Check for log too.
I was in the same situation. For me deleting existing eclipse installation(not not the project workspace) and opening the existing eclipse workspace with new installation of eclipse was the only thing that worked.
Just copy the project as a new one. Configure the build path by creating new Run/Debug Settings.this would resolve the problem.
I continued to get the "no resources selected" error. I then did the procedure I am quoting and it gave me a MANIFEST file. Then I was able to create an executable JAR.
Quoting: "I exported the project as an archive file. Then I opened up a new workspace and imported the the archived project. After that I tried to export the project as a runnable jar, after two tries the jar runs as is it should."
I also faced the same issue, in my case, I just closed the project and reopened it, now it's wokring
Check that your project is correct at the time when you select the main class.
If the class non exist, it's the standard error of Eclipse.

Eclipse giving errors whenever I try to export to executable jar

I'm trying to export a small program that I have made in Eclipse Indigo today to an executable, however, every time I do so one of two problems occur. The program uses one resource which I was hoping to put inside of the JAR but Eclipse will not put in the executable jar no matter which option I tick when I export or which folder the resource is in - the first problem!
The second problem is that whenever I tell eclipse to "Extract required libraries into generated JAR" I receive the following error when I double click on the executable Jar:
Could not find the main class: main.Launcher. Program will exit.
I don't suppose that the second problem is too much of an issue at the minute but the first one is extremely frustrating so I would appreciate any help or advice. Thanks in advance.
(Strangely, and even more frustrating, if I go through the same process with a project I made a while ago with a previous version of Eclipse it works perfectly.)
The folder structure of the project is as follows:
In the project folder there are the following directories .settings, bin, src as default. I have put the resource, which is a png in the bin folder but I have also tried it in the src folder.
Can you give some details?
What is the structure of your eclipse project?
Of what type is the resource?
More important where in the project structure resides the resource file?
Is the folder of that resource file included as a source folder ? (seems to be a prerequiste to get exported to the jar)
Is it copied over to the bin folder when the project is built?
Many Thanks
Michael
Update:
I have built a very simple java project 1 Java class with a main method and put a sample png file in the source folder. I refreshed the project to have the png visible in the project, then I cleaned the project to have it build again, then I ran the Main class inside eclipse. This will give you a run configuration when exporting throught the wizard. Thereafter I exported the complete project as "runnable jar", selected the run configuration and selected "Copy required libraries in a sub-folder next to the generated JAR". The png was included and the Main class was found. The executable JAR could be executed.
(Environment: Eclipse Indigo R1, Ubuntu, JDK 6)
You might want to play through the complete sequence of steps I went through. Maybe eclipse just did not pick up a file or other updates.
regards, Mike
First of all, I would like to thank Mike (marksml) for being so helpful and attempting to provide a solution for my problem. Unfortunately, his answer did not work for me!
I began to look at all of my previous projects and noticed that the one I was having trouble with was the odd one out (because it was the only one that didn't work) and the factor that made it the odd one out, I found to be the JRE system library version. The project was using the JavaSE-1.7 library but when I changed it to the JavaSE-1.6 like my other projects were using it miraculously worked and exported flawlessly! I'm still curious as to why this is the case, but at least I have it working now...
With thanks and kind regards, Andy

Categories

Resources