1. 程式人生 > >Java程式如何正確打包並正常執行在Linux系統中

Java程式如何正確打包並正常執行在Linux系統中

需求:將本地Java程式部署到linux伺服器並執行,首先要將本地Java程式打成jar包,然後拷貝到伺服器後執行java -jar xx.jar
問題:該程式本地執行正常,服務端執行報錯找不到第三方包中的類
原因:本地打jar包時有錯,未能正確引入第三方包
解決:本地通過fat jar外掛來打包,方法如下

在Eclipse 下 java 應用程式打包 Mainfest.mf 格式

首先保證程式在Eclipse下的正常執行,然後方法如下:

( 寫在最前面 做好的Eclipse打包 還是使用外掛 Fat jar)
下載地址 :http://sourceforge.net/project/showfiles.php?group_id=115990&package_id=125924

使用說明:
Fat Jar Eclipse Plug-In Tutorial Step 1: Create a new Java Project "demolib"

Create a new Java Project named "demolib".
Add the Class "demolib.DemoLib.Java" containing the following code:

package demolib;

public class DemoLib {
public static void sayHello() {
System.out.println("Hello");
}
}

The Project should look something like this:


Step 2: Create a jar file using Fat Jar Plug-In

In the "Package-Explorer" (not the "Resource-View") right click on the project "demolib".
Select "+ Build Fat Jar".


A Configuration Dialog appears. Just press "Finish".


The File "demolib_fat.jar" has been created in the project root directory.


Step 3: Create a new Java-Project "demorun"

Create a new Java Project named "demorun".
In the project properties add the Library "demolib/demolib_fat.jar" to the Java Build Path":


Step 4: Create Main Class

Add the Class "demorun.DemoRunMain.java" containing the following code:

package demorun;

import demolib.DemoLib;

public class DemoRunMain {
public static void main(String[] args) {
DemoLib.sayHello();
}
}

The Project should look something like this:


Step 5: Start the Build Fat Jar Dialog

Start the Export Wizard from the File-Menu ("File" -> "Export").
Select "+ Fat Jar Exporter" and click "next >". 


Select the project "demorun" and click "next >".


A Configuration-Dialog appears showing the current Settings.


Step 6: Select the Main Class

The Main Class - the one containing the static methode main - must be defined in the jar.
Click on the "Browse..." Button on the right side behind the Main-Class Edit field.


Select "DemoRunMain" and click the "OK" Button.
The FullyQualifiedName "demorun.DemoRunMain" is now set for "Main-Class".

Step7: Finish

Save the current Settings by clicking on the "Finish" Button.


The File "demorun_fat.jar" has been created in the project root directory.
In addition the file ".fatjar" storing the configuration settings has been created in the project root directory

The created jar file contains all classes from all referenced jar files (demolib_fat.jar) and the project classes.
This file can be executed anywhere, no classpath has to be set, because all necessary libraries
are extracted inside the "Fat Jar": 

> java -jar demorun_fat.jar
Hello