问题
I wrote a program that spans a few classes in IntelliJ and it works fine when I was testing it in the IDE. However, whenever I follow tutorials to make my project into a .jar executable, it does not run.
The file in the out folder does not run when double-click on it and says "The Java JAR file "projectName.jar" could not be launched.
When opening it from the terminal, I get the error "Could not find or load main class". I used "$ java -jar projectName.jar "
I followed these steps:
- Open Project Structure, Artifacts and click the (+).
- Under JAR, from modules with dependencies.
- Point to the class with my main method and click OK.
- Click apply and OK to exit.
- Then I close project structure and open Build and then Build Artifacts...
- Then I click Build.
- Navigate to ~/IdeaProjects/projectName/out/artifacts/projectName_jar/projectName.jar
Then I would try to run it but it does not run. My project has both a GUI and can be run from command lines. When I compiled the main method in Terminal, it worked fine, but I need a JAR file. I'm not sure what I should include in the question, since I'm sure that my code is unrelated. I also utilize Maven, not sure if that is related. Are there other things that I should be doing or adding to my project before I build the JAR?
回答1:
This can be a result of the Manifest being created in the wrong place.
First make sure it is in src/main/resources/META-INF/MANIFEST.MF
(Intellij sometimes incorrectly places it in /src/main/java/META-INF/MANIFEST.MF
)
Then Make sure the jar is looking for META-INF in the src dir NOT in /java OR /resources. This means:
When you set up File>Project Structure>Artifacts>+>JAR>From modules with dependencies... then your Directory for META-INF/MANIFEST.MF should end at src
. Example:
ONLY C:\Users\User\StudioProjects\Project\src\
NOT THE PREPOPULATED C:\Users\User\StudioProjects\Project\src\main\java
If your Project Structure jar is already set up change the Manifest File path to:
C:\Users\User\StudioProjects\Project\src\META-INF\MANIFEST.MF
INSTEAD OF C:\Users\User\StudioProjects\Project\src\main\java\META-INF\MANIFEST.MF
回答2:
You need to make sure that the Main-Class attribute is set. One way to check this is by opening the Jar with a Zip utility and looking for META-MF/MANIFEST.MF
extract or open that file with a notepad, notepad++ or any document reader. If "Main-Class" is not in their or set to the correct main class you will received the error you have received. Seeing the IntelliJ tutorial it has a Main-Class field when setting up artifact publishing. I have included the link below to the IntelliJ page.
IntelliJ Creating an Artifact Tutorial
来源:https://stackoverflow.com/questions/37276146/jar-files-created-by-intellij-idea-do-not-run