gpt4 book ai didi

java - 从 Java 执行 Shell 脚本,具有读取操作的 Shell 脚本

转载 作者:行者123 更新时间:2023-11-29 09:34:26 32 4
gpt4 key购买 nike

我有一个读取输入的 Shell 脚本

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

我正在使用 JAVA API 执行此 shell 脚本

ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/junk/leaptest.sh");
final Process process = pb.start();

InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;


while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");

在 Java 控制台中我可以看到输出

Type the year that you want to check (4 digits), followed by [ENTER]:

现在的实际问题是如何将值传递给脚本中的 Shell 脚本如何读取变量“year”


我已经按照建议编辑了代码,但在我们更正它的地方不起作用

ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "/junk/leaptest.sh");
final Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
/*
* OutputStream os = process.getOutputStream(); PrintWriter pw = new
* PrintWriter(os);
*/

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
while ((line = br.readLine()) != null) {
System.out.println(line);
// pw.println("8999");
bw.write("2012");
}
System.out.println("Program terminated!");

最佳答案

您可以使用 Process 类的 OutputStream:

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

pw.println("1997");

您写入此输出流的内容将成为 shell 脚本的输入流。所以 read year 会将 1987 读取到 year 变量。

编辑:

我也试了一下,终于找到了问题所在。 1997 字符串尚未到达脚本,因为 PrintWriter 缓冲了写入它的数据。您必须在 println() 之后使用 pw.flush() 刷新 PrintWriter 流,或者您必须设置 auto-flush 属性创建时为 true:

PrintWriter pw = new PrintWriter(os, true);

这是对我来说工作正常的完整代码:

leaptest.sh:

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

测试.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();
}
}
}

输出:

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

关于java - 从 Java 执行 Shell 脚本,具有读取操作的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810943/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com