Executing Shell Scripts from Java, Shell scripts having read operation

前端 未结 5 1270
再見小時候
再見小時候 2020-12-16 08:36

I have a Shell Scripts that read the Input

#!/bin/bash
echo \"Type the year that you want to check (4 digits), followed by [ENTER]:\"
read year
echo $year  
         


        
5条回答
  •  猫巷女王i
    2020-12-16 08:58

    You can use the OutputStream of the Process class:

    OutputStream os = process.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    
    pw.println("1997");
    

    What you write to this output stream will become the input stream of the shell script. So read year will read 1987 to the year variable.

    EDIT:

    I also tried it out and I've managed to find the problem. The 1997 string hasn't reached the script, beacuse PrintWriter buffers the data that was written to it. You either have to flush the PrintWriter stream after the println() with pw.flush() or you have to set the auto-flush property to true upon creation:

    PrintWriter pw = new PrintWriter(os, true);
    

    Here is the complete code that was working fine for me:

    leaptest.sh:

    #!/bin/bash
    echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
    read year
    echo $year
    

    Test.java:

    import java.io.*;
    
    class Test {
    
        public static void main(String[] args) {
            try {
                ProcessBuilder pb = new ProcessBuilder("/bin/bash", "leaptest.sh");
                final Process process = pb.start();
    
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                PrintWriter pw = new PrintWriter(process.getOutputStream());
                String line;
    
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    pw.println("1997");
                    pw.flush();
                }
                System.out.println("Program terminated!");
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Output:

    $ java Test
    Type the year that you want to check (4 digits), followed by [ENTER]:
    1997
    Program terminated!
    

提交回复
热议问题