在我的 java 代码中,我创建了执行某些 shell 命令的场景,实际上特别是执行了 -scp-
和 -mv-
命令。
是否可以记录执行结果?例如,如果找不到要复制的文件,或者 -scp-
或 -mv-
没有正确出现,它会记录到我准备的日志文件中。目前我的命令执行代码如下:
if ("command") {
String command = "mv " + source_file_path + "/"
+ " " + dest_file_path;
Process child = Runtime.getRuntime().exec(command);
exitVal = child.waitFor();
// Get the input stream and read from it
InputStream in = child.getInputStream();
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int c = bis.read();
while (c != -1) {
byte b = (byte) c;
buf.write(b);
c = bis.read();
}
in.close();
System.out.println("Input Stream: " + buf.toString());
buf.close();
bis.close();
InputStream ein = child.getErrorStream();
BufferedInputStream ebis = new BufferedInputStream(ein);
ByteArrayOutputStream ebuf = new ByteArrayOutputStream();
int ce = ebis.read();
while (ce != -1) {
// process((char)c);
byte be = (byte) ce;
ebuf.write(be);
ce = ebis.read();
}
ein.close();
System.out.println("Error Stream: " + ebuf.toString());
ebuf.close();
ebis.close();
}
System.exit(0);
无论如何我可以在上面添加一个日志组件吗?记录找不到文件、文件传输不正确、文件传输有问题等
最佳答案
解析您在名为 buf
的 ByteArrayOutputStream 中捕获的命令输出以确定结果,并将其记录下来。您也可以从 exit code of the process 中获得线索。 ,您将其存储在 exitVal
中。
请注意,通过在读取 stdout 和 stderr 流之前调用 child.waitFor(),您可以保证如果进程的输出变得太大,这将不会起作用。根据 Process API docs : "由于某些原生平台只为标准输入输出流提供了有限的缓冲区大小,未能及时写入子进程的输入流或读取输出流可能会导致子进程阻塞,甚至死锁。"
关于java - 将命令行参数记录到 log4j 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7808933/