杰瑞科技汇

Linux下Java main方法如何正确运行?

Of course! The phrase "Linux Java main" can refer to several related concepts. I'll break it down into the most common interpretations, from running a simple Java program to more advanced topics.

Linux下Java main方法如何正确运行?-图1
(图片来源网络,侵删)

Let's start with the most fundamental: running a Java program with a main method on a Linux system.


Part 1: The Basics - Running a Java main Method on Linux

This is the core of your question. It involves writing a simple Java program, compiling it, and then executing it from the Linux command line.

Step 1: Write the Java Code

First, you need a Java source file with a main method. The main method is the entry point for any standalone Java application.

Create a file named HelloWorld.java:

Linux下Java main方法如何正确运行?-图2
(图片来源网络,侵删)
// File: HelloWorld.java
public class HelloWorld {
    // This is the main method. It's the entry point of the program.
    public static void main(String[] args) {
        // Print "Hello, Linux!" to the console.
        System.out.println("Hello, Linux!");
        // You can also use command-line arguments
        if (args.length > 0) {
            System.out.println("You provided an argument: " + args[0]);
        } else {
            System.out.println("No arguments provided.");
        }
    }
}

Key points:

  • The file name must match the public class name (HelloWorld.java for the HelloWorld class).
  • The method signature public static void main(String[] args) is required.
  • System.out.println() prints text to the standard output (your terminal).

Step 2: Open a Terminal

Open your Linux terminal. You can usually do this with Ctrl+Alt+T or by searching for "Terminal" in your application menu.

Step 3: Compile the Code

Use the Java compiler, javac, to turn your .java source file into Java bytecode (a .class file).

In your terminal, navigate to the directory where you saved HelloWorld.java and run:

Linux下Java main方法如何正确运行?-图3
(图片来源网络,侵删)
javac HelloWorld.java

If the command succeeds, you will see a new file in the directory: HelloWorld.class. This is the bytecode that the Java Virtual Machine (JVM) can execute.

Step 4: Run the Code

Now, use the java command to run your compiled program. The java command starts the JVM, which loads your class and executes its main method.

java HelloWorld

Important Note: Notice that you do not include the .class extension when running the program. You are telling the java command which class to run, not which file to execute.

Expected Output:

Hello, Linux!
No arguments provided.

Step 5: Using Command-Line Arguments

You can pass arguments to your Java program from the command line. These arguments are passed to the String[] args array in the main method.

Try running the program again with an argument:

java HelloWorld "This is a test"

Expected Output:

Hello, Linux!
You provided an argument: This is a test

Part 2: Creating an Executable JAR File

For larger applications, you don't want to run java com.mycompany.Main every time. You can package your class(es) into a JAR (Java Archive) file and make it executable.

Step 1: Create a Manifest File

The manifest file tells the JVM which class contains the main method. Create a file named manifest.txt:

# File: manifest.txt
Main-Class: HelloWorld

(Note: There must be a blank line at the end of the manifest.txt file).

Step 2: Package into a JAR

Use the jar command to create the archive. The cvmf flags mean:

  • c: create a new JAR file
  • v: generate verbose output (optional)
  • m: include the manifest file from the specified file
  • f: specify the output JAR file name
jar cvmf manifest.txt HelloWorld.jar HelloWorld.class

This creates HelloWorld.jar.

Step 3: Run the Executable JAR

Now you can run your application directly from the JAR file.

java -jar HelloWorld.jar

Expected Output:

Hello, Linux!
No arguments provided.

You can also pass arguments to the JAR:

java -jar HelloWorld.jar "Argument from JAR"

Part 3: Advanced Topics & Best Practices

As you get more comfortable, you'll encounter these common scenarios on Linux.

Managing Java Versions (update-alternatives)

Linux systems often have multiple Java versions installed (e.g., OpenJDK 8, 11, 17). You need to switch between them.

  • Check installed versions:

    java -version
    javac -version
  • See available alternatives:

    sudo update-alternatives --config java
    sudo update-alternatives --config javac

    This will show you a menu to select which version to use as the default.

Building with Maven or Gradle

For any non-trivial project, you use a build automation tool. Maven and Gradle are the most popular. They handle:

  • Compiling code.
  • Downloading dependencies (libraries from the internet).
  • Running tests.
  • Packaging the application (e.g., into a JAR or a "fat" JAR that includes all dependencies).

A simple Maven project structure looks like this:

my-java-app/
├── pom.xml              // Maven configuration file
└── src/
    └── main/
        └── java/
            └── com/
                └── mycompany/
                    └── App.java

You would then run your application from the project's root directory (my-java-app/) using Maven commands:

# Compile the code and download dependencies
mvn compile
# Run the main class
mvn exec:java -Dexec.mainClass="com.mycompany.App"
# Package the application into a JAR
mvn package

3: Running as a Linux Service (systemd)

To make your Java application run in the background, start on boot, and restart automatically if it crashes, you should run it as a Linux service.

Create a service file: Create a file named my-java-app.service in /etc/systemd/system/.

# File: /etc/systemd/system/my-java-app.service
[Unit]
Description=My Awesome Java Application
After=network.target
[Service]
# The user and group that will run the service
User=myuser
Group=mygroup
# The working directory
WorkingDirectory=/path/to/your/app
# The command to start the application
# Use the full path to java and your jar file
ExecStart=/usr/bin/java -jar /path/to/your/app/HelloWorld.jar
# Restart the service if it exits
Restart=on-failure
[Install]
WantedBy=multi-user.target

Manage the service:

# Reload the systemd daemon to read the new service file
sudo systemctl daemon-reload
# Start the service
sudo systemctl start my-java-app
# Enable the service to start on boot
sudo systemctl enable my-java-app
# Check the status of your service
sudo systemctl status my-java-app
# View the logs (very useful for debugging)
sudo journalctl -u my-java-app -f

Summary

Concept Command Purpose
Compile javac MyClass.java Turns source code (.java) into bytecode (.class).
Run java MyClass Executes the bytecode of the specified class.
Run with Args java MyClass arg1 arg2 Passes command-line arguments to the main method.
Build JAR jar cvmf manifest.jar MyApp.jar MyClass.class Packages .class files into an executable archive.
Run JAR java -jar MyApp.jar Executes the main class defined in the JAR's manifest.
Build (Maven) mvn package Compiles code, downloads deps, and builds a distributable artifact.
Run as Service sudo systemctl start my-app.service Manages the lifecycle of your app as a background service.
分享:
扫描分享到社交APP
上一篇
下一篇