Chapter 26. Using Java with Other Languages
Introduction
Java has several methods of running programs written in other
languages. You can invoke a compiled program or executable script using
Runtime.exec( )
, as I’ll describe in Recipe 26.1. Or you can drop
down to C level with Java’s "native code” mechanism and call compiled functions written
in C/C++. From there, you can call to functions written in
just about any language. Not to mention that you can contact programs
written in any language over a socket (see Chapter
17), with HTTP services (see Chapter 18), or with Java clients in
RMI or CORBA clients in a variety of languages (see Chapter 22).
There is an element of system dependency here, of course. You can only run Windows applications under Windows and Unix applications under Unix. So some of the recipes in this chapter aren’t portable, although in a few cases I try to make them at least run on Windows or Unix.
26.1. Running a Program
Problem
You want to run a program.
Solution
Use one of the exec( )
methods in the java.lang.Runtime
class. Or, on JDK 1.5, use the start( )
method of ProcessBuilder
.
Discussion
The exec( )
method in the
Runtime
class lets you run an
external program. The command line you give is broken into strings by a simple StringTokenizer
(Recipe 3.2) and passed on to
the operating system’s “execute a program” system call. As an example,
here is a simple program that uses exec(
)
to run kwrite
, a windowed text editor program.[1] On Windows, you’d have to ...
Get Java Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.