简体   繁体   中英

Create a java executable with Eclipse

This is a totally newbie question. I'm running Eclipse on Ubuntu. I created a test project that I want to compile to an executable (whataver the linux equivalent is of a Windows .exe file). Here's the contents of my program:

public class MyTest {
    public static void main(String[] args) {

        System.out.println("You passed in: " + args[0]);

    }
}

I want to know how to compile it and then how to execute it from the command line.

Thanks!

You need to create an executable JAR file. Steps will follow shortly.

Right click on the project and select JAR file under Export.

在此输入图像描述

Enter the path where you want it to be saved. The example here is of Windows. Change according to your platform.

在此输入图像描述

Click Next.

在此输入图像描述

Edit the Main Class field by browsing and selecting the location of your class that contains the main method.

在此输入图像描述

Run it

To run the JAR file, open up a shell or command prompt and execute the following command:

java -jar path/to/test.jar

In Eclipse, choose file then export, and you will have to choose runnable jar. Also, you will be prompted to select the main class, MyTest in your case.

Eclipes教程非常有用,如果您执行“创建Hello World应用程序”教程,它将引导您完成设置项目,构建应用程序和运行jar文件的过程。

I want to know how to compile it ...

See other answers on how to get Eclipse to create a JAR file.

... and then how to execute it from the command line.

In the simple case, you execute it by running java -jar yourApp.jar <args> .

If your application depends on external libraries, then it is a bit more complicated ...

how come I would choose jar file over executable jar file?

  • Because a JAR file is portable, and a binary executable is not.
  • Because JIT compiled code runs faster than code that is compiled ahead of time.
  • Because the standard Java tool chain does not support creation of binary executables. Ditto for Eclipse, AFAIK.

Marked solution does not work. Use "runnable" jar instead and then java -jar <jarfile>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM