try
{
Processprocess=Runtime.getRuntime().exec("ls");
InputStreamReaderir=newInputStreamReader(process.getInputStream());
LineNumberReaderinput=newLineNumberReader(ir);
Stringline;
while((line=input.readLine())!=null){
System.out.println(line)
}
catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());
}
Java可以直接調用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
舉例:運行ls,top命令可以這樣:
Runtime.getRuntime().exec("ls");
但是這樣執行時沒有任何輸出,原因:
調用Runtime.exec方法將產生一個本地的進程,並返回一個Process子類的實例,
(注意:Runtime.getRuntime().exec(command)返回的是一個Process類的實例),
該 實例可用於控制進程或取得進程的相關信息. 由於調用Runtime.exec方法所創建的子進程沒有自己的終端或控制台,因此該子進程的標准IO(如stdin,stdou,stderr)都通過 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream()方法重定向給它的父進程了.用戶需要用這些stream來向子進程輸入數據或獲取子進程的輸出. 可以採用如上方法:
② Java開發人員應掌握Linux哪些方面
1在linux配置java,tomcat環境變數,因為j2ee一般服務都是架設在linux上面的
2簡單的shell操作(相當於dos命令行),比如刪除,查找文件,進入某一個目錄基本操作等等
3會設置linux開機自啟動程序,因為mysql等服務安裝完後,開機自動啟動服務需要自己設置的
4懂得linux下的一些常用程序vi,gedit,telnet,openoffice等的常用執行命令和程序
③ java中如何執行linux命令
執行linux命令基,基本思路是從控制台獲得輸入的指令,啟動命令行執行命令,捕捉異常,示例如下:
publicclassTestRunTime{
publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{
Stringcmd="";
if(args==null||args.length==0){
System.out.println("請輸入命令行參數");
}else{
for(inti=0;i<args.length;i++){//獲得輸入的命令
cmd+=args[i]+"";
}
}
try{
Processprocess=Runtime.getRuntime().exec(cmd);//執行命令
InputStreamReaderir=newInputStreamReader(process.getInputStream());
LineNumberReaderinput=newLineNumberReader(ir);
Stringline;
while((line=input.readLine())!=null){//輸出結果
System.out.println(line);
}
}catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());//捕捉異常
}
}
}
④ java程序里調用linux命令
Java語言以其跨平台性和簡易性而著稱,在Java裡面的lang包里(java.lang.Runtime)提供了一個允許Java程序與該程序所運
行的環境交互的介面,這就是Runtime類,在Runtime類里提供了獲取當前運行環境的介面。
其中的exec函數返回一個執行shell命令的子進程。exec函數的具體實現形式有以下幾種:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
我們在這里主要用到的是第一個和第四個函數,具體方法很簡單,就是在exec函數中傳遞一個代表命令的字元串。exec函數返回的是一個Process類
型的類的實例。Process類主要用來控制進程,獲取進程信息等作用。(具體信息及其用法請參看Java doc)。
1)執行簡單的命令的方法:
代碼如下:
⑤ 在linux下如何用命令行的形式執行Java程序
1、java程序一般都有啟動腳本
2、例如tomcat/bin
./startup.sh
3、例如weblogic
./startWebLogic.sh
4、也可以用java直接啟動jar包,例如
/doyoo/jdk1.6/bin/java -DRmode=test -Dlog4j.configuration=file:conf/log4j.properties -classpath run.jar net.test.ji
m.server.boot.Booter
⑥ 如何在java程序中調用linux命令或者shell腳本
java程序是提供了這個一方法,Processpro=Runtime.getRuntime().exec(cmds);
但是一般來說,盡量去用一些其他腳本(lua,shell,python)去執行一系列linux命令比較靈活, 而且耗費資源少。但是Runtime.getRuntime().exec()這種調用方式在java虛擬機中是十分消耗資源的,即使命令可以很快的執行完畢,頻繁的調用時創建進程消耗十分可觀。
java虛擬機執行這個命令的過程是,首先克隆一條和當前虛擬機擁有一樣環境變數的進程,再用這個新的進程執行外部命令,最後退出這個進程。頻繁的創建對CPU和內存的消耗很大。
下面是一個調用linux命令的例子:
publicclassTest{
publicstaticvoidmain(String[]args)throwsException{
String[]cmds={"/bin/sh","-c","ps-ef|grepjava"};
Processpro=Runtime.getRuntime().exec(cmds);
pro.waitFor();//阻塞,直到上述命令執行完
InputStreamin=pro.getInputStream();
BufferedReaderread=newBufferedReader(newInputStreamReader(in));
Stringline=null;
while((line=read.readLine())!=null){
System.out.println(line);
}
}
}
⑦ 怎麼用java代碼運行linux命令
以下方法支持Linux和windows兩個系統的命令行調用。還用到了apache的lang工具包commons-lang3-3.1.jar來判斷操作系統類型、也用到了和log4j-1.2.16.jar來列印日誌。至於rm -rf 是否能成功刪除文件,可以手動去調用命令行試試。
privateStringcallCmd(Stringcmd)throwsInterruptedException,UnHandledOSException,ExecuteException{
if(SystemUtils.IS_OS_LINUX){
try{
//使用Runtime來執行command,生成Process對象
Processprocess=Runtime.getRuntime().exec(
newString[]{"/bin/sh","-c",cmd});
intexitCode=process.waitFor();
//取得命令結果的輸出流
InputStreamis=process.getInputStream();
//用一個讀輸出流類去讀
InputStreamReaderisr=newInputStreamReader(is);
//用緩沖器讀行
BufferedReaderbr=newBufferedReader(isr);
Stringline=null;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(java.lang.NullPointerExceptione){
System.err.println("NullPointerException"+e.getMessage());
logger.error(cmd);
}catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());
}
thrownewExecuteException(cmd+"執行出錯!");
}
if(SystemUtils.IS_OS_WINDOWS){
Processprocess;
try{
//process=newProcessBuilder(cmd).start();
String[]param_array=cmd.split("[\s]+");
ProcessBuilderpb=newProcessBuilder(param_array);
process=pb.start();
/*process=Runtime.getRuntime().exec(cmd);*/
intexitCode=process.waitFor();
InputStreamis=process.getInputStream();
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderbr=newBufferedReader(isr);
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
thrownewExecuteException(cmd+"執行出錯!");
}
thrownewUnHandledOSException("不支持本操作系統");
}
⑧ 如何在java程序中調用linux命令或者shell腳本
在java程序中如何調用linux的命令?如何調用shell腳本呢?
這里不得不提到java的process類了。
process這個類是一個抽象類,封裝了一個進程(你在調用linux的命令或者shell腳本就是為了執行一個在linux下執行的程序,所以應該使用process類)。
process類提供了執行從進程輸入,執行輸出到進程,等待進程完成,檢查進程的推出狀態,以及shut down掉進程。
至於詳細的process類的介紹放在以後介紹。
另外還要注意一個類:Runtime類,Runtime類是一個與JVM運行時環境有關的類,這個類是Singleton的。
這里用到的Runtime.getRuntime()方法是取得當前JVM的運行環境,也是java中唯一可以得到運行環境的方法。(另外,Runtime的大部分方法都是實例方法,也就是說每次運行調用的時候都需要調用到getRuntime方法)
下面說說Runtime的exec()方法,這里要注意的有一點,就是public Process exec(String [] cmdArray, String [] envp);這個方法中cmdArray是一個執行的命令和參數的字元串數組,數組的第一個元素是要執行的命令往後依次都是命令的參數,envp感覺應該和C中的execve中的環境變數是一樣的,envp中使用的是name=value的方式。
下面說一下,如何使用process來調用shell腳本
例如,我需要在linux下實行linux命令:sh test.sh,下面就是執行test.sh命令的方法:
這個var參數就是日期這個201102包的名字。
String shpath="/test/test.sh"; //程序路徑
Process process =null;
String command1 = 「chmod 777 」 + shpath;
process = Runtime.getRuntime().exec(command1);
process.waitFor();
String var="201102"; //參數
String command2 = 「/bin/sh 」 + shpath + 」 」 + var;
Runtime.getRuntime().exec(command2).waitFor();
注意:
1
我為什麼要使用 chmod 777命令呢?在有的機器上面,可能沒有設置許可權問題。這是你在linux下面執行shell腳本需要注意的問題。沒有的話,就需要添加許可權,就用chmod 777,否則在執行到Runtime.getRuntime().exec的時侯會出現Permission denied錯誤。
2
waitFor()這個也是必不可缺的,如果你需要執行多行命令的話,把waitFor()這個加上。
⑨ java程序執行linux命令
首先確保Linux開啟sshd服務,並支持遠程SSH連接。java程序使用jsch框架登錄Linux,執行命令。
protected void creation() throws Exception {
JSch jsch = new JSch();
session = jsch.getSession(userName, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(CONNECT_TIMEOUT);
session.setConfig("PreferredAuthentications", "password,keyboard-interactive");
session.setServerAliveInterval(1000 * 60 * 2);
session.connect();
}
public String sendCommand(String command) throws Exception {
if(!isConnected())
throw new JSchException("Session is not connected, command exec faild.");
final ChannelExec exec = (ChannelExec)session.openChannel("exec");
ByteArrayOutputStream out = new ByteArrayOutputStream();
exec.setCommand(command);
exec.setOutputStream(out);
exec.setExtOutputStream(out);
exec.connect();
final Thread thread = new Thread() {
public void run() {
while(!exec.isEOF()) {
try { Thread.sleep(500L); } catch(Exception e) {}
}
}
};
thread.setDaemon(true);
thread.start();
thread.join(EXEC_TIMEOUT);
thread.interrupt();
if(thread.isAlive()) {
throw new JSchException("Exec Time Out Error");
} else {
try {
exec.disconnect();
out.close();
} catch (Exception e) {
}
byte[] lens = out.toByteArray();
String result = new String(lens, charset);
if(result.startsWith("bash") && result.indexOf("command not found") != -1)
return "";
return result;
}
}
⑩ 在Java中如何操作linux命令行運行.sql文件
連接linux,
可以使用工具如filezilla ,x5等上傳 你的sql文件到linux伺服器上
登錄mysql
復制代碼代碼如下:
>mysql -u root -p
>password:
注意,如果你之前建立了其他的mysql用戶,可以選擇合適的用戶登錄。
按照下面的三個步驟,快速導入這個sql文件
復制代碼代碼如下:
mysql>use yourdatabasename;
mysql>set names utf8;
mysql>source /tmp/database.sql;
然後屏幕上就會不斷的滾,最後提示導入成功。
最後,記得將database.sql刪除。