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

How Can I Execute a Command Line in Java?

Linda Hamilton
Release: 2024-12-17 11:31:25
Original
558 people have browsed it

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
Copy after login

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
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template