java调用Shell脚本

本文介绍如何使用Java程序来调用并执行UNIX/Linux系统中的Shell脚本,包括设置脚本执行权限、通过Runtime类执行脚本及读取输出结果的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://hi.baidu.com/qiu1157/blog/item/6b4f02362a7c0c360b55a9e3.html

在你的test.sh的第一行加入
#!/bin/sh

 然后在shell下运行chmod a+x test.sh就可以把你的test.sh变成可执行文件了。
另外,要提醒的是你的java程序运行的目录和你shell用户可能不同,所以建议用全路径,比如
Runtime.getRuntime().exec ("/root/bin/test.sh");

----------------------------------------------------------------------------------------------

如果需要输出信息的话   

   Process process = Runtime.getRuntime().exec("/root/bin/test.sh");
   InputStreamReader ir = new InputStreamReader(process.getInputStream());
   LineNumberReader input = new LineNumberReader(ir);
   String line;
   while ((line = input.readLine()) != null)
    System.out.println(line);
   input.close();
   ir.close();

-----------------------------------------------------------------------------------------------

注意UNIX系统的权限问题 =..=

-----------------------------------------------------------------------------------------------

完整代码:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class RunShell {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   //Runtime.getRuntime().exec("/root/bin/test.sh");
   Process process = Runtime.getRuntime().exec("/root/bin/test.sh");
   InputStreamReader ir = new InputStreamReader(process
     .getInputStream());
   LineNumberReader input = new LineNumberReader(ir);
   String line;
   while ((line = input.readLine()) != null)
    System.out.println(line);
   input.close();
   ir.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值