Home >Java >javaTutorial >How Can I Execute a Command Line in Java?

How Can I Execute a Command Line in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 11:31:25559browse

How Can I Execute a Command Line in Java?

Executing Command Lines in Java

In Java, accessing the command line is possible using the Runtime.exec() method. By utilizing this method, Java applications can execute command lines that would otherwise require manual execution in the terminal.

Problem:

A user wishes to execute the following command line within a Java application:

java -jar map.jar time.rel test.txt debug

Solution:

To execute this command line in Java, follow these steps:

import java.lang.Runtime;
import java.lang.Process;

public class CommandLineRunner {

    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

        // Handle the process output or error (if any) here
        
        pr.waitFor();  // Wait for the command to finish
    }
}

For more information on using Runtime.exec(), refer to the link: http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

The above is the detailed content of How Can I Execute a Command Line in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn