![](/img/trans.png)
[英]Read .txt file from maven project in java using executable file in linux shell
[英]Maven - Executable file from a java project
我需要使用maven(用於學校項目)從單個maven命令創建可執行文件。 我從未使用過maven,並在stackoverlow上嘗試了很多解決方案。 解決方案創建了一個jar文件,但該文件從未打開過。
這是我的項目結構
src
com
project
code
swing
programm
interface
Main.class
我知道這不是maven慣例,但現在更改它意味着我必須調整導入(因為intelliJ不能完美地重構所有內容)大約40個類。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MyGroup</groupId>
<artifactId>myProgramm</artifactId>
<version>0.7-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Hello World</name>
<description>Course Project</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.25.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit/junit5-engine -->
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-engine</artifactId>
<version>5.0.0-ALPHA</version>
</dependency>
</dependencies>
<build>
</build>
我需要做什么來制作可執行文件?
您需要將插件添加到pom.xml
文件中
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>com.example.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
並運行程序: mvn clean install exec:java
...這里是doc http://www.mojohaus.org/exec-maven-plugin/usage.html的鏈接
可能有不同的解決方案,取決於您的要求: https : //www.baeldung.com/executable-jar-with-maven
TimurJD的答案是正確的,但我想逐步解釋實際發生的事情和原因。
要使jar可執行,JVM需要知道main
方法的位置。
為此,您需要在您創建的jar中使用名為META-INF / MANIFEST.MF的文件。
此文件必須包含對包含main
方法的類的引用,如下所示:
Main-Class: com.example.ClassContainingMainMethod
有很多方法可以創建所述文件,但是因為你在這里使用maven是一個插件,可以幫助你創建這個清單文件
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.1</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.my.packege.Main</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build>
在pom.xml
插入插件后,只需從IDE或命令行運行maven install
目標即可。 在項目中找到名為target
的文件夾之后。 該文件夾將包含可執行jar。
要運行jar,您可以從命令行調用:
java -jar MyProject.jar
還應該注意,除非您遵守將源代碼保存在src/main/java
的maven標准,否則您必須明確指定源文件夾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.