java执行外部程序获得程序输出,java执行外部输出,下面代码演示如何使用ja
java执行外部程序获得程序输出,java执行外部输出,下面代码演示如何使用ja
下面代码演示如何使用java来执行外部程序的子进程,然后获得子进程的输出:
import java.io.*;public class CmdExec { public static void main(String argv[]) { try { String line; Process p = Runtime.getRuntime().exec (System.getenv("windir") +"\\system32\\"+"tree.com /A"); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); } catch (Exception err) { err.printStackTrace(); } }}
下面进程演示如何使用cmd.exe,获得输入输出流和子进程交互
String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; // launch EXE and grab stdin/stdout and stderr Process process = Runtime.getRuntime ().exec ("/folder/exec.exe"); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the parms into stdin line = "param1" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param2" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param3" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); stdin.close(); // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stdout] " + line); } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stderr] " + line); } brCleanUp.close();
// win xpimport java.io.*;public class CmdExec { public static void main(String argv[]) { try { String line; Process p = Runtime.getRuntime().exec("test.cmd"); p.waitFor(); System.out.println(p.exitValue()); } catch (Exception err) { err.printStackTrace(); } }}
test.cmd (set the errorlevel manually)
@echo hello world@exit 42
test.cmd (set the errorlevel 1 (problem detected)
@java -garbage
test.cmd (set the errorlevel 0 (execution Ok)
@java -version
Launch a Unix script
String[] cmd = {"/bin/sh", "-c", "ls > hello"};Runtime.getRuntime().exec(cmd);
Using the ProcessBuilder Since 1.5, the ProcessBuilder class provides morecontrols overs the process to be started. It's possible to set a startingdirectory.
import java.io.*;import java.util.*;public class CmdProcessBuilder { public static void main(String args[]) throws InterruptedException,IOException { List<String> command = new ArrayList<String>(); command.add(System.getenv("windir") +"\\system32\\"+"tree.com"); command.add("/A"); ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> environ = builder.environment(); builder.directory(new File(System.getenv("temp"))); System.out.println("Directory : " + System.getenv("temp") ); final Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } System.out.println("Program terminated!"); }}
Windows rundll32 utility Windows File association Any program using theWindows file association mechanism can be started with the rundll32 utility.
// "file" is the filename of the data file // ex. myresume.doc // to start Word if the doc extension is associated with it.Runtime.getRuntime().exec ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file.getAbsolutePath());
See also this HowTo aboutthe new Desktop API, the recommended solution (but you need JDK1.6). See alsothis one to open thedefault browser.
The following example start a Dial-up connection on the Win plateform :
[Dialup.java]public class Dialup { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime() .exec("rundll32.exe rnaui.dll,RnaDial MyConnection"); p.waitFor(); System.out.println("Done."); }}
The "MyConnection" is the DUN and it's case sensitive. You still need to pressENTER to CONNECT, there is an option in the Connection properties to connectautomatically.
On NT and W2K, rnaui.dll is not available. Use rasdial.exe instead.
rasdial "connection name"rasdial "connection name" /d to droprasdial /? for more options
PDF (Windows only)
public class ShowPDF { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime() .exec("rundll32 url.dll,FileProtocolHandler c:/pdf/mypdf.pdf"); p.waitFor(); System.out.println("Done."); }}
PDF (Mac only)
public class ShowPDF { public static void main (String[] args) throws Exception{ Process p = Runtime.getRuntime().exec("open /Documents/mypdf.pdf"); }}
For paths to executable with spaces you can include a path for the program tobe executed. On the Win platform, you need to put the path in quotes if thepath contains spaces.
public class Test { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime().exec( "\"c:/program files/windows/notepad.exe\""); p.waitFor(); }}
If you need to pass arguments, it's safer to a String array especially if theycontain spaces.
String[] cmd = { "myProgram.exe", "-o=This is an option" };Runtime.getRuntime().exec(cmd);
If using the start command and the path of the file to be started contains aspace then you must specified a title to the start command.
String fileName = "c:\\Applications\\My Documents\\test.doc";String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};Runtime.getRuntime().exec(commands);
VBSCRIPT
// Win9xRuntime.getRuntime().exec("start myscript.vbs");// WinNTRuntime.getRuntime().exec("cmd /c start myscript.vbs");or// with a visible consoleRuntime.getRuntime().exec("cscript myscript.vbs");// with no visible consoleRuntime.getRuntime().exec("wscript myscript.vbs");
HTML Help (Windows only)
Runtime.getRuntime().exec("hh.exe myhelpfile.chm");
Start Excel
import java.io.IOException;class StartExcel { public static void main(String args[]) throws IOException { Runtime.getRuntime().exec("cmd /c start excel.exe"); }}
To load a worksheet
import java.io.IOException;class StartExcel { public static void main(String args[]) throws IOException { String fileName = "c:\\temp\\xls\\test2.xls"; String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName}; Runtime.getRuntime().exec(commands); }}
It's important to pass a dummy title to the Windows start command where thereis a possibility that the filename contains a space. It's a feature. Start aWindows application under another account You use the RUNAS command from thecommand line to start an application under another account (not available withXP Home edition). There are many switches that can enhance the behaviour ofRUNAS. Typing "runas /?" from the command prompt gets you all the options.
String commands [] = new String [] { "CMD.EXE", "/C", "RUNAS /profile /savecred /user:" + "administrator" + " " + "regedit.exe" }; Runtime.getRuntime().exec(commands);
/SaveCred option allows you to save a password for that account and then reuseit later. For example, The command runas /savecred /user:administratorregedit.exe prompts for the password, and then Regedit runs. Next time you usethe same command, there is no password prompt. One potential problem is thatwhen /SaveCred saves the credentials it saves it for whenever RUNAS invokesthat user account. This can be a huge security risk so be careful using it!
RUNAS capability can be disabled by editing the Registry or by disabling theRUNAS or Secondary Logon Services. The appropriate registry key isHKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer, create a newDWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as.
RUNAS doesn't work when used from a Windows service.
Windows : execute something in Program Files We want to execute the textpadeditor located in C:\Program Files\TextPad 4 but without hard coding the pathsince it can be different for a localized version of Windows. We simplyextract to environnment variable called %programfiles% and build the completepath from there.
[JDK1.5]
public class Exec { static String WIN_PROGRAMFILES = System.getenv("programfiles"); static String FILE_SEPARATOR = System.getProperty("file.separator"); public static void main(String[] args) throws Exception { String[] commands = {"cmd.exe", "/c", WIN_PROGRAMFILES + FILE_SEPARATOR + "textpad 4" + FILE_SEPARATOR + "textpad.exe"}; Runtime.getRuntime().exec(commands); }}
NOTE : Prior Vista, System folders were localized on disk like C:\ProgramFiles -> C:\Archivos de programa on the Windows with the Spanish localization.Since Vista, System Folders always exists with the english name BUT whenviewed through Explorer, the localized name is shown. Seehttp://msmvps.com/blogs/carlosq/archive/2007/02/12/windows-vista-junctions-points-mui-and-localized-folder-names.aspx
用户点评