2016-09-30 37 views
-3

執行我使用此代碼到我的java程序獲取bash腳本的輸出值與Java

pb.environment().put("time", time); 
pb.environment().put("value", value); 
Process p = pb.start();  
p.waitFor(); 
// get the return value 

內執行一個腳本等待的過程是有可能得到的輸出值之後?輸出值是指腳本中使用的回波值

+3

http://stackoverflow.com/questions/5711084/java-runtime-getruntime-getting-output-from-executing-a-command-line-program –

回答

0

嘗試類似這樣;

test.sh

#!/bin/bash 
echo $time 
echo $value 

java類;

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

public class RunShellScript { 
    public static void main(String[] args) { 

     String command = "/tmp/test.sh"; 
     try { 
      ProcessBuilder pb = new ProcessBuilder(command); 

      Calendar cal = Calendar.getInstance(); 
      SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
      String time = sdf.format(cal.getTime()); 
      String value = "your Value"; 


      pb.environment().put("time", time); 
      pb.environment().put("value", value); 

      Process p = pb.start(); 
      p.waitFor(); 

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(
        p.getInputStream())); 

      BufferedReader stdError = new BufferedReader(new InputStreamReader(
        p.getErrorStream())); 

      // to standard output 
      String s = null; 
      while ((s = stdInput.readLine()) != null) { 
       System.out.println(s); 
      } 

      // to standard error 
      while ((s = stdError.readLine()) != null) { 
       System.out.println(s); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

} 

Java控制檯輸出:

16:03:03 
your Value