Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Create and Run JAR Files on Linux

In the Linux environment, JAR (Java ARchive) files are a common way to package and distribute Java applications. Understanding how to create and run JAR files is essential for Java developers and system administrators working in a Linux environment. This article will guide you through the process of creating a JAR file from Java source code and running it via the command line on a Linux system.

Examples:

  1. Creating a JAR File:

    To create a JAR file, you first need to compile your Java source code into bytecode using the javac command. Then, you use the jar command to package the compiled classes into a JAR file.

    • Step 1: Compile Java Source Code

      javac MyProgram.java

      This command compiles MyProgram.java into MyProgram.class.

    • Step 2: Create the JAR File

      jar cvf MyProgram.jar MyProgram.class

      This command creates a JAR file named MyProgram.jar containing the MyProgram.class file. The options used are:

      • c: Create a new JAR file.
      • v: Generate verbose output.
      • f: Specify the JAR file name.
  2. Running a JAR File:

    Once you have created the JAR file, you can run it using the java command with the -jar option.

    • Step 1: Run the JAR File
      java -jar MyProgram.jar

      This command runs the MyProgram.jar file.

  3. Creating an Executable JAR File:

    If your Java program has a main method, you can create an executable JAR file by specifying the Main-Class attribute in a manifest file.

    • Step 1: Create a Manifest File Create a file named manifest.txt with the following content:

      Main-Class: MyProgram

      Ensure there is a newline at the end of the file.

    • Step 2: Create the Executable JAR File

      jar cvfm MyProgram.jar manifest.txt MyProgram.class

      This command creates an executable JAR file named MyProgram.jar with the specified manifest file.

    • Step 3: Run the Executable JAR File

      java -jar MyProgram.jar

      This command runs the executable JAR file.

  4. Automating the Process with a Script:

    You can automate the process of compiling and creating JAR files using a shell script.

    • Step 1: Create a Shell Script Create a file named build.sh with the following content:

      #!/bin/bash
      javac MyProgram.java
      jar cvfm MyProgram.jar manifest.txt MyProgram.class
    • Step 2: Make the Script Executable

      chmod +x build.sh
    • Step 3: Run the Script

      ./build.sh

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.