我尝试使用How to redirect Process Builder's output to a string?中的解决方案阅读过程并发现错误,但它没有输出任何内容。
在开始流程之前,是否有办法将流阅读器附加到流程构建器?
/*
private String getInputAsString(InputStream is)
{
try(java.util.Scanner s = new java.util.Scanner(is))
{
return s.useDelimiter("\\A").hasNext() ? s.next() : "";
}
}
*/
private static BufferedReader getOutput(Process p) {
return new BufferedReader(new InputStreamReader(p.getInputStream()));
}
private static BufferedReader getError(Process p) {
return new BufferedReader(new InputStreamReader(p.getErrorStream()));
}
List<String> args = new ArrayList<String>();
args.add ("cmd"); // command name
args.add ("/c");
args.add ("start");
args.add (fileName);
ProcessBuilder pb = new ProcessBuilder (args);
pb.directory(new File(Support.getJustThePathFromFile(file)));
Map<String, String> envs = pb.environment();
String path = envs.get("Path");
envs.put("Path", Paths.get(".").toAbsolutePath().normalize().toString() + ";" +path);
//pb.redirectOutput(new Redirect() {});
Process p = pb.start();
//String stdOut = getInputAsString(p.getInputStream());
//String stdErr = getInputAsString(p.getErrorStream());
//System.err.println("stdOut=" + stdOut);
//System.err.println("stdErr=" + stdErr);
try
{
p.waitFor();
BufferedReader output = getOutput(p);
BufferedReader error = getError(p);
String ligne = "";
while ((ligne = output.readLine()) != null) {
System.out.println(ligne);
}
while ((ligne = error.readLine()) != null) {
System.out.println(ligne);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}