How to execute Linux command from Java app.

Hi all,Could anyone show me how to execute Linux command from Java app. For example, I have the need to execute the "ls" command from my Java app (which is running on the Linux machine), how should I write the codes?Thanks a lot,
[257 byte] By [huytruc] at [2007-9-26 1:47:41]
# 1
use java.io.File to get a filelist...File myFile = new File("myPath");File[] myFileList = myFile.listFiles();hope this helps..
susieM at 2007-6-29 2:47:02 > top of Java-index,Archived Forums,Java Programming...
# 2
Try using Runtime.exec().For example:Runtime.getRuntime.exec("ls");But remember that the command you are trying to execute must ba a standalone program and not a shell command. Don't forget the proper path.Robert
rthomanek at 2007-6-29 2:47:02 > top of Java-index,Archived Forums,Java Programming...
# 3
See also http://www.javaworld.com/jw-12-2000/jw-1229-traps.html on general programming pifalls on Runtime.exec.
jsalonen at 2007-6-29 2:47:02 > top of Java-index,Archived Forums,Java Programming...
# 4

You can use "built-in" shell commands, you just need to invoke the shell and tell it to run the command. See the -c switch in the man page for your shell. But, "ls" isn't built-in anyays.

If you use exec, you will want to set the directory with the dir argument to exec, or add it to the command or cmdarray. See the API for the variants of java.lang.Runtime.exec(). (If you're invoking it repeatedly, you can most likely modify a cmdarray more efficiently than having exec() decompose your command).

You will also definitely want to save the returned Process and read the output from it (possibly stderr too and get an exit status). See API for java.lang.Process. Here's an example

java.io.BufferedReader br =

new java.io.BufferedReader(new java.io.InputStreamReader(

Runtime.getRuntime().exec ("/sbin/ifconfig ppp0").

getInputStream()));

while ((s = br.readLine()) != null) {...

blaine.simpson at 2007-6-29 2:47:02 > top of Java-index,Archived Forums,Java Programming...
# 5
Wrtie=fasdfa
mwstein at 2007-6-29 2:47:03 > top of Java-index,Archived Forums,Java Programming...