歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell 跟Java 相互調用和獲取結果

Shell 跟Java 相互調用和獲取結果

日期:2017/3/1 11:08:09   编辑:SHELL編程

被調用的shell

a.sh

Shell代碼

  1. #!/bin/bash
  2. echo 111
  3. exit 8

java 代碼

  1. public static void main(String[] args) throws IOException {
  2. Process p = Runtime.getRuntime().exec(command);
  3. InputStream is = p.getInputStream();
  4. int data;
  5. StringBuffer strBuffer = new StringBuffer();
  6. while ((data = is.read()) != -1) {
  7. strBuffer.append((char) data);
  8. }
  9. System.out.println("命令:\n" + command);
  10. System.out.println("結果:\n" + p.exitValue());
  11. System.out.println("log:\n" + strBuffer.toString());
  12. int ret = p.exitValue(); // 全路徑
  13. System.exit(ret); // 直接返回shell執行的結果
  14. }

調用java的shell

test.sh

  1. #!/bin/bash
  2. #調用java打包後的jar文件
  3. java -jar test.jar
  4. #顯示執行結果
  5. echo $?
Copyright © Linux教程網 All Rights Reserved