Progress-servis55.ru

Новости из мира ПК
4 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java runtime exec

When Runtime.exec() won’t

Navigate yourself around pitfalls related to the Runtime.exec() method

Now, let’s follow the JDK documentation and handle the output of the javac process. When you run javac without any arguments, it produces a set of usage statements that describe how to run the program and the meaning of all the available program options. Knowing that this is going to the stderr stream, you can easily write a program to exhaust that stream before waiting for the process to exit. Listing 4.3 completes that task. While this approach will work, it is not a good general solution. Thus, Listing 4.3’s program is named MediocreExecJavac ; it provides only a mediocre solution. A better solution would empty both the standard error stream and the standard output stream. And the best solution would empty these streams simultaneously (I’ll demonstrate that later).

Listing 4.3 MediocreExecJavac.java

A run of MediocreExecJavac generates:

So, MediocreExecJavac works and produces an exit value of 2 . Normally, an exit value of 0 indicates success; any nonzero value indicates an error. The meaning of these exit values depends on the particular operating system. A Win32 error with a value of 2 is a «file not found» error. That makes sense, since javac expects us to follow the program with the source code file to compile.

Running system commands in Java applications

UPDATE: This article has been replaced by my newer «Java exec with ProcessBuilder and Process» article. While the Java code shown in this tutorial works on simple «Java exec» cases, the new article shows how to properly read the output streams from your system command in Java threads, and also how to write to your command’s standard input, if necessary.

Feel free to read this article for background/legacy information, but I strongly recommend that you use the source code I’m sharing in my newer «Java exec» article, because it resolves the standard input, output, and error problems that I didn’t handle properly in the code below.

Introduction

I’ve read a lot about Java but one of the things I rarely see discussed is how you should go about running external system commands. Of course, you probably don’t read much about this because it takes away from the portability of Java applications. For instance, if you write a Java application on a Unix system, you might be interested in running the «ps -ef» command, and reading the output of the command. For Unix systems this is great, but unfortunately, this same program won’t work on a Windows system because the ps command isn’t available on Windows.

Well, we’re going to forget about portability for this article, and demonstrate a method that can be used to run system commands. We’ve received a lot of requests about this topic, so here goes.

Discussion (Runtime exec and Process)

Executing a system command is relatively simple — once you’ve seen it done the first time. It involves the use of two Java classes, the Runtime class and the Process class. Basically, you use the exec method of the Runtime class to run the command as a separate process. Invoking the exec method returns a Process object for managing the subprocess. Then you use the getInputStream() and getErrorStream() methods of the Process object to read the normal output of the command, and the error output of the command. What you do with the output of the command executed is entirely up to you and the application you’re creating.

(Note: There is also a getOutputStream() method that you can use to write to the process, but we won’t cover that method in this article. We’ll cover that and a few other advanced features in a future article.)

A Java exec example

The code shown in Listing 1 provides a working example of our «Java exec» technique in a file named JavaRunCommand.java .

Listing 1 (above): The file JavaRunCommand.java shows how you can run an external system command from within a Java program.

How our Java exec code works

The first thing you do is specify the command you want to run by supplying this command to the Runtime class. Because you can’t create your own instance of the Runtime class, you first use the getRuntime method to access the current runtime environment and then invoke the Runtime exec method. This returns a Process object.

Everything else you do involves methods of the Process object. In this case, because we’re running the «ps -ef» command on a Unix system, we just need to read the output of the command. Reading the standard error probably isn’t required in this case, but I thought at the very least it was at least worth showing, if not good programming practice.

Читать еще:  Java socket connect

I convert the input streams with the InputStreamReader and BufferedReader so I can use the readLine() method of the BufferedReader class. Because I use these classes, this application will not compile properly with an older JDK 1.0.x compiler (these classes weren’t available in 1.0.x).

Download the «Java exec» example source code

I could go on at length about this topic, but the best thing I can recommend is that you download the source code and work with it for a while. Try running different commands to see if you can get them to work properly, and try to run a command that requires input (this will be a bit more complicated).

How to Run a Shell Command in Java

Last modified: January 13, 2020

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

With this tutorial we’ll illustrate the two ways of executing a shell command from within Java code.

The first is to use the Runtime class and call its exec method.

The second and more customizable way, will be to create and use a ProcessBuilder instance.

2. Operating System Dependency

Before we’re going to create a new Process executing our shell command, we need to first determine the operating system on which our JVM is running.

That’s because, on Windows, we need to run our command as argument to the cmd.exe shell and on all other operating systems we can issue a standard shell, called sh:

3. Input and Output

Furthermore we need a way to hook into the input and output streams of our process.

At least the output must be consumed – otherwise our process doesn’t return successfully, instead it will hang.

Let’s implement a commonly used class called StreamGobbler which consumes an InputStream:

NOTE: This class is implementing the Runnable interface, which means that it could be executed by any Executor.

4. Runtime.exec()

A method-call to Runtime.exec() is a simple, not yet customizable, way to spawn a new sub-process.

In the following example we will request a directory-listing of a users home-directory and printing it to the console:

5. ProcessBuilder

For the second implementation of our computing problem, we’ll be using a ProcessBuilder. This is preferred over the Runtime approach because we’re able to customize some details.

For example we’re able to:

  • change the working directory our shell command is running in using builder.directory()
  • set-up a custom key-value map as environment using builder.environment()
  • redirect input and output streams to custom replacements
  • inherit both of them to the streams of the current JVM process using builder.inheritIO()

6. Conclusion

As we’ve seen in this quick tutorial, we can execute a shell command in Java in two distinct ways.

Generally, if you’re planning to customize the execution of the spawned process, for example, to change its working directory, you should consider using a ProcessBuilder.

As always, you’ll find the sources on GitHub.

Java.lang.Runtime class in Java

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

Methods of Java Runtime class :

1) public static Runtime getRuntime() : This method returns the instance or Runtime object associated with the current Java application.

2) public long freeMemory() : This method returns the amount of free memory in the JVM(Java Virtual Machine)

3) public long totalMemory() : This method returns the amount of total memory in the JVM(Java Virtual Machine)

4) public Process exec(String command)throws IOException : This method executes given command in a separate process.

Exception :

1)SecurityException : If a security manager exists and its checkExec method doesn’t allow creation of the subprocess

2)IOException : If an I/O error occurs

3)NullPointerException : If command is null

4)IllegalArgumentException : If command is empty

Note : Replace with any software you want to start. I work on Linux and google-chrome is written like this way only. May differ in windows/mac.

5) public void addShutdownHook(Thread hook) : This method registers a new virtual-machine shutdown hook thread.

Читать еще:  Выборочному наблюдению присущи ошибки

Exception :

1) IllegalArgumentException : If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run

2) IllegalStateException :If the virtual machine is already in the process of shutting down

3) SecurityException : If a security manager denies RuntimePermission(“shutdownHooks”)

6) public boolean removeShutdownHook(Thread hook) : This method de-registers a previously-registered virtual-machine shutdown hook.

7) public int availableProcessors() : This method returns the number of processors available to the JVM (Java virtual machine).

8) public void exit(int status) : This method terminates the currently running Java virtual machine by initiating its shutdown sequence.

9) public void traceInstructions(boolean a) : This method enables or disables tracing of instructions. If the boolean argument is true then it will suggests that the JVM (Java virtual machine) emits debugging information for each instruction in the virtual machine as it is executed.

10) public void traceMethodCalls(boolean a) : This method enables or disables tracing of method calls. If the boolean argument is truethen it will suggests that the Java virtual machine emit debugging information for each method in the virtual machine as it is called.

11) public void loadLibrary(String libname) : This method loads the dynamic library with the specified library name. A file containing code is loaded from the local system from a place where library files are conventionally obtained.

Exception :

1) UnsatisfiedLinkError : if the library does not exist.

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

12) public void load(String filename) : This method Loads the specified filename as a dynamic library. The filename argument must be a complete path name.

Exception :

1) UnsatisfiedLinkError : if the library does not exist.

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

13) public void gc() : This method runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

14) public void runFinalization() : This method runs the finalization methods of any objects pending finalization. It suggests that HVM (Java virtual machine) expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.

15) public long maxMemory() : This method returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

16) public void halt(int status) : This method forcibly terminates the currently running Java virtual machine. This method never returns normally. This method should be used with extreme caution.

Exception :

SecurityException : If a security manager is present and its checkExit method does not permit an exit with the specified status

17) public Process exec(String[] cmd) : This method executes the specified command and arguments in a separate process. This is a convenience method.

Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

18) public Process exec(String command, String[] envp, File dir) : This method Executes the specified string command in a separate process with the specified environment and working directory. This is a convenience method.

Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

19) public Process exec(String command, String[] envp) : This method executes the specified string command in a separate process with the specified environment. This is a convenience method and behaves in exactly the same way as the invocation exec(command, envp, null).
Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

20) public Process exec(String[] cmdarray, String[] envp, File dir) : This method executes the specified command and arguments in a separate process with the specified environment and working directory. Given an array of strings cmdarray, representing the tokens of a command line, and an array of strings envp, representing “environment” variable settings, this method creates a new process in which to execute the specified command.
Exception :

1) IndexOutOfBoundsException : If cmd is an empty array (has length 0)

2) NullPointerException : if libname is null.

3) SecurityException : if checkLink method doesn’t allow loading of the specified dynamic library.

4) IOException : If an I/O error occurs

Ссылка на основную публикацию
Adblock
detector