Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to call other programs from Java programs

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to call other programs from the Java program, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

How Rmi (Remote Method Invocation, remote method invocation) is used for inter-program communication. Another technology for communication is the Runtime.exec () method. You can use this method to call another program from one running a java program. Runtime.exec also allows you to perform operations related to the program, such as controlling the standard input and output of the program, waiting for the program to end and getting its exit status. Here is a simple C program to illustrate these features:

XML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" / >

# include

Int main () {

Printf ("testingn")

Return 0

}

This program writes the string "testing" to standard output and then terminates the program with exit status 0.

To execute this simple program in the java program, compile the c program first

$cc test.c-o test

(translator's note: for Linux users, you can use gcc test.c-o test, and the corresponding windows users can compile the program into an executable program test.exe with the corresponding c language.)

(your C compiler may require different parameters) and then use the following code to call that program:

Import java.io.*

Import java.util.ArrayList

Public class ExecDemo {

Static public String [] runCommand (String cmd)

Throws IOException {

/ / set up list to capture command output lines

ArrayList list = new ArrayList ()

/ / start command running

Process proc = Runtime.getRuntime () .exec (cmd)

/ * * translator's note: the previous statement should be changed to java.lang.Process, that is:

Java.lang.Process proc = Runtime.getRuntime () .exec (cmd)

If you don't change it, you may compile differently. If you use jdk1.2 on the translator's machine, there are 5 errors in compilation.

4 errors occurred in compiling with jdk1.4

, /

/ / get command's output stream and

/ / put a buffered reader input stream on it

InputStream istr = proc.getInputStream ()

BufferedReader br =

New BufferedReader (new InputStreamReader (istr))

/ / read output lines from command

String str

While (str = br.readLine ())! = null)

List.add (str)

/ / wait for command to terminate

Try {

Proc.waitFor ()

}

Catch (InterruptedException e) {

System.err.println ("process was interrupted")

}

/ / check its exit value

If (proc.exitValue ()! = 0)

System.err.println ("exit value was non-zero")

/ / close stream

Br.close ()

/ / return list of strings to caller

Return (String []) list.toArray (new String [0])

}

Public static void main (String args []) throws IOException {

Try {

/ / run a command

String outlist [] = runCommand ("test")

/ / display its output

For (int I = 0; I < outlist.length; iTunes +)

System.out.println (outlist [I])

}

Catch (IOException e) {

System.err.println (e)

}

}

}

The demo program calls the method runCommand to actually run the program.

String outlist [] = runCommand ("test")

This method uses an input stream to hook up the program's output stream, so it can read the program's output and store it in a list of strings.

InputStream istr = proc.getInputStream ()

BufferedReader br =

New BufferedReader (new InputStreamReader (istr))

String str

While (str = br.readLine ())! = null)

List.add (str)

After all the output has been read, call waitFor to wait for the program to terminate, and then call exitValue to read the exit status value of the program. If you have done a lot of system programming, such as unix system calls, this method should be familiar to you. This example assumes that the current path is included in the execution path of your shell.

If you use the UNIX system, you can use:

RunCommand ("ls-l")

Instead of:

RunCommand ("test")

(translator's note: a more general one is runCommand ("java"); the translator uses runCommand ("dir"); the result is a program IO exception under Windows2000, which has not been tested under linux. )

Gets a long list of all files under the current path. But getting a list in this way highlights a basic weakness in using Runtime.exec-the program you call becomes non-portable. In other words, Runtime.exec is portable and exists in different java implementations, but the called program is not necessarily the case. There is no program called "ls" in the Windows system.

Suppose you run windows NT and you decide to use

RunCommand ("dir")

To correct this problem, "dir" is the equivalent of "ls". This does not work because "dir" is not an executable program. It is built into the shell (command interpreter) CMD.EXE. So you should use:

RunCommand ("cmd / c dir")

Where "cmd / c command" is "call shell and execute the specified command and exit." Similarly, for a UNIX shell, such as Korn shell, you might want to use:

RunCommand ("ksh-c alias")

Here "alias" is the built-in command of shell. The output in this case is a list of aliases for shell.

In the above example of getting a directory list, you can use a portable java program to achieve the same result. For example:

Import java.io.File

Public class DumpFiles {

Public static void main (String args []) {

String list [] = new File (".") .list ()

For (int I = 0; I < list.length; iTunes +)

System.out.println (list [I])

}

}

Gives a list of all files and directories in the current directory. So in most cases, using ls/dir may not make sense.

One situation that makes use of Runtime.exec makes sense is to allow the user to specify an editor or word processor (such as Emacs or Vi or word) to edit the file. This is a common feature of large programs. The program will have a configuration file that specifies the local path to the editor, and then use that path to call Runtime.exec.

One of the subtleties of Runtime.exec is how it finds files. For example, you use:

Runtime.exec ("ls")

So how can "ls" be found? Experiments on JDK 1.2.2 show that it is a search for PATH environment variables. This is just like what happens when you execute commands in shell. However, this is not stated in the documentation, so it should be used with care. You can't assume that the search path has been set. As discussed above, it may make more sense to use Runtime.exec in limited ways, using absolute paths.

There are also different Runtime.exec that allow you to specify an array of environment strings.

The above is all the contents of the article "how to call other programs from Java programs". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report