开发者

What is the purpose of Process class in Java?

开发者 https://www.devze.com 2022-12-29 12:54 出处:网络
Runtime objRuntime = Runtime.getRuntime(); String strBackupString =开发者_运维知识库 \"mysqldump -u \" + userName + \" -p\" + password + \" \" + dbName;
Runtime objRuntime = Runtime.getRuntime();
String strBackupString =开发者_运维知识库 "mysqldump -u " + userName + " -p" + password + " " + dbName;
Process objProcess = objRuntime.exec(strBackupString);

This is used for backup of database. But what exactly happens? Can anybody make me explain, what is the purpose of Runtime and Process class?

Is this class used to act as if we are typing command from command prompt? Then what should i pass to objRuntime.exec() if i want to open notepad? And is the command executed as soon as we call exec method? If yes, then what purpose does Process serve here? I really can't understand these two classes. Please make me understand. Thanks in advance :)


Whenever in doubt, always consult the API:

java.lang.Process

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

Runtime.exec(String command)

Executes the specified system command in a separate process.

So yes, Runtime.exec can execute a command that you'd usually type in the system command prompt. This is hardly a platform-independent solution, but sometimes it's needed. The returned Process object lets you control it, kill it, and importantly sometimes, redirect its standard input/output/error streams.

Related questions

  • Is java Runtime.exec platform independent?
  • How to create a process in Java
  • Get output from a process
  • Runtime.getRuntime().exec()

API links

  • java.lang.Process
  • java.lang.ProcessBuilder
  • java.lang.Runtime

notepad.exe example

As mentioned before, this is platform dependent, but this snippet works on my Windows machine; it launches notepad.exe, and attempts to open test.txt from the current working directory. The program then waits for the process to terminate, and prints its exit code.

public class ExecExample {
    public static void main(String[] args) throws Exception {
        Process p = Runtime.getRuntime().exec("notepad.exe test.txt");      
        System.out.println("Waiting for notepad to exit...");
        System.out.println("Exited with code " + p.waitFor());
    }
}


It's an object-based representation of a process. Similar to the Thread class, which represents a thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号