从Linux计算机中的Java类以交互方式运行Shell脚本

时间:2018-10-08 06:00:27

标签: java shell

我有一个简单的shell脚本,可以打印“ Hello world”,向用户询问一个数字并打印该数字。 我正在尝试使用运行时和进程从linux计算机中的Java类运行此脚本。 但是,当我使用java命令从Linux命令行在Linux机器上运行此Java类时,它将打印前两行,并在从用户处获取输入时挂起。我无法将任何输入传递给脚本。

请让我知道如何通过java交互式运行脚本。下面是我的脚本和Java类文件:

sample.sh

#!/bin/sh
echo "Hello world"
echo "Enter any number"
read response
echo "The number you entered is: $response"

ExecuteScript.java

package com.scripting;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class ExecuteScript {
    public static void main(String args[]) {
        System.out.println("Java program ran!!");
        String[] cmdScript = new String[]{"/bin/bash", "/root/sample.sh"};
        Process procScript = null;

        try {

            procScript = Runtime.getRuntime().exec(cmdScript);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        InputStream ip = procScript.getInputStream();
        OutputStream op = procScript.getOutputStream();
        BufferedReader reader = new BufferedReader(new 
        InputStreamReader(ip));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(op));
        BufferedReader consoleReader =  
            new BufferedReader(new InputStreamReader(System.in));

        try {
            while(reader.readLine() != null) {

                    if(!reader.ready()) {
                        String input = consoleReader.readLine();
                        writer.write(input);
                        writer.flush();
                    }else {
                        System.out.println(reader.readLine());
                    }

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

0 个答案:

没有答案