當要調用一個外部程序的時候,java提供了exec方法,具體用法是:Runtime.getRunTime.exec("cmd /C Start mailto: ").其中cmd /c是調用cmd下的start命令,它至關於對一個文件雙擊。也能夠用Runtime.getRunTime.exec("c:\\EXCEl.exe d:\\a.xls")來打開D盤下的excel文件. java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; 工具
public class test { 網站
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Runtime rn=Runtime.getRuntime();
Process p= null;
try {
//p = rn.exec( "cmd /k dir ");
p = rn.exec( "C:\\Windows\\system32\\notepad.exe f:\\gg.txt");
InputStream in =p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str = null;
while((str=br.readLine())!= null){
System.out.println(str);
}
br.close();
} catch (Exception e) {
System.out.println( "Error exec notepad ");
}
}
} .net
/*
public class Test { 命令行
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
/*public static void main(String[] args) throws IOException, InterruptedException
{
// TODO 自動生成方法存根
Process process = Runtime.getRuntime().exec("C:\\Program Files\\Microsoft Office\\Office12\\winword.exe f:\\gg.docx");
//process.waitFor( );cmd /c java f:\\T
/*String ls_1;
Process process = Runtime.getRuntime().exec("cmd /c dir ");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ( (ls_1=bufferedReader.readLine()) != null)
System.out.println(ls_1); */
//C:\\Program Files\\Microsoft Office\\Office12\\winword.exe
// C:\Program Files\Microsoft Office\Office12\winword.exe
/*
process.waitFor( );
//process.destroy(); excel
} get
}*/ cmd
Process process = Runtime.getRuntime().exec("cmd /c del f:\\aaa.doc"); it
這樣的調用是沒有問題~ io
真正最正確的用BAT運行JAVA不顯示DOS窗口(連閃一下都不閃)
今天寫一個獨立於RCP項目以外的SWT小工具,須要用批處理啓動,偶寫了一個批處理沒閃DOS窗口,看得同事一愣一愣的。因而趕快把本身當年一點心得和你們分享下。
不少朋友在WINDOWS下會用批處理去啓動本身的java程序,
通常的寫法是
運行class:
java xx
運行jar:
java -jar xxx.jar
可是這樣運行會有一個噁心的對話框停在那直到咱們關閉程序。
因而不少人說能夠這樣
運行class:
start javaw xx
運行jar:
start javaw -jar xxx.jar
這種方法DOS窗口仍是會一閃而過,這就算解決問題了嗎?!網上不少人說是的.
對咱們這種追求完美的人來講閃一下仍是不能接受滴.
因而終極解決方案出現了!
那就是在批處理第一行加上@echo off
這樣咱們的批處理就變成了
運行class:
@echo off
start javaw xx
運行jar:
@echo off
start javaw -jar xxx.jar
快試試吧,絕對不閃了。哈哈哈。
解釋一下
echo off
表示在此語句後全部運行的命令都不顯示命令行自己
@ 表示運行時不顯示本命令行
public class TestCmd {
public TestCmd() {
}
public static void main(String args[]) {
try {
// 登網站
Process process = Runtime.getRuntime().exec(
"cmd.exe /c start http://www.hao123.net/"); // 使用用Ping命令 Process ee = Runtime.getRuntime().exec( "cmd.exe /c start ping 10.5.2.19"); } catch (Exception e) { e.printStackTrace(); } } } 運行這個類你會看到效果 這個是運行了ping命令 我使用Process pc = Runtime.getRuntime().exec("cmd /c ping 127.0.0.1");能夠成功;