linux java 调用 shell java 调用 linux .sh

原文转自:http://wangbaoaiboy.blog.163.com/blog/static/52111910201111892938552/

1.Java调用shell
  
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)执行简单的命令的方法:
代码如下:
       
try            
String commands = "ls -l";
           
Process process = Runtime.getRuntime().exec (commands);
           
// for showing the info on screen
           
InputStreamReader ir=new
InputStreamReader(process.getInputStream());
           
BufferedReader input = new BufferedReader (ir);
           
String line;
           
while ((line = input.readLine ()) != null){
               
System.out.println(line);
       
}//end try
       
catch (java.io.IOException e){
           
System.err.println ("IOException " + e.getMessage());
       
}   上面的代码首先是声明了一个代表命令的字符串commands,它代表了ls -l
这个命令。之后我们用Runtime.getRuntime().exec(commands)来生成一个子进程来执行这个命令,如果这句话运行成功,则
命令 ls -l 运行成功(由于没有让它显示,不会显示ls -l
的结果)。后面的流操作则是获取进程的流信息,并把它们一行行输出到屏幕。2)执行带有参数的命令(尤其是参数需要用引号的)时则需要用String的数组来表示整个命令,而且要用转义符把引号的特殊含义去除,例如我们要执行
find / -name "*mysql*" -print 时,用如下代码
       
try            
String[] commands = new
String[]{"find",".","-name","*mysql*","-print"};
           
Process process = Runtime.getRuntime().exec (commands);
           
InputStreamReader ir=new
InputStreamReader(process.getInputStream());
           
BufferedReader input = new BufferedReader (ir);
           
String line;
           
while ((line = input.readLine ()) != null){
               
System.out.println(line);
        
}//end try
       
catch (java.io.IOException e){
           
System.err.println ("IOException " + e.getMessage());

 

Java 可以通过 Runtime 调用Linux命令,形式如下:

Runtime.getRuntime().exec(command)

但是这样执行时没有任何输出,因为调用 Runtime.exec 方法将产生一个本地的进程,并返回一个Process子类的实例(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例)该实例可用于控制进程或取得进程的相关信息。

由于调用 Runtime.exec 方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向给它的父进程了。

用户需要用这些stream来向子进程输入数据或获取子进程的输出,下面的代码可以取到 linux 命令的执行结果:

try {
String[] cmd = new String[]{”/bin/sh”, “-c”, ” ls “};
Process ps = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append(”\n”);
}
String result = sb.toString();

System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过Java调用.sh脚本,你可以使用Runtime类的exec方法来执行shell命令。可以使用以下代码来执行.sh脚本: String[] cmd = { "sh", "/path/to/script.sh", "parameter1", "parameter2" }; try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println("line = " + line); } reader.close(); } catch (Exception e) { e.printStackTrace(); } 在这段代码中,我们定义了一个字符串数组cmd,其中第一个元素是"sh",表示使用shell来执行命令,第二个元素是"/path/to/script.sh",表示要执行的.sh脚本的路径,后面的参数可以根据需要进行更改。然后通过Runtime类的exec方法执行这个命令,最后通过BufferedReader来读取命令的输出并打印出来。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [java调用shell脚本传参数](https://blog.csdn.net/weixin_57463074/article/details/127802692)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [使用java执行bat、sh脚本文件](https://blog.csdn.net/gxy6661159/article/details/128615151)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值