我想保存使用java执行的命令的整个命令行日志,我正在使用它通过API将其发送到不同的程序。在Eclipse中,我们可以通过设置输出文件,通过运行时配置来实现这一点。那么,有没有一种方法可以发送命令行执行的整个输出,并将其保存在外部文件中?
发布于 2020-01-29 07:49:32
通过java代码运行命令的基本示例
public static void main(String[] argv) throws Exception {
String command = "ls";
Process child = Runtime.getRuntime().exec(command);
InputStream in = child.getInputStream();
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String line;
while((line=br.readLine())!=null){
bw.write(line);
bw.newLine();
}
bw.close();
}发布于 2020-01-29 07:59:38
java应用程序只知道传递给它的参数;它对JVM选项、动态环境设置(即-Dname=value)等一无所知。
要查看整个命令,您必须使用操作系统命令来查看正在运行的进程并检查其输出。
例如,在linux中,使用long pid = ProcessHandle.current().pid();,然后使用args "-p", pid执行"ps",然后解析输出。
发布于 2021-08-24 06:43:33
我的两点意见详细阐述了桑迪普·帕特尔的答案。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class Os {
public static boolean exec(String command, String filePath) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
return true;
} catch (IOException e) {
return false;
}
}
public static String exec(String command) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringWriter sw = new StringWriter()) {
String line;
while ((line = br.readLine()) != null)
sw.write(line + "\n");
return sw.toString();
} catch (IOException e) {
return null;
}
}
public static String exec2(String command) {
try (InputStream in = Runtime.getRuntime().exec(command).getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
return sb.toString();
} catch (IOException e) {
return null;
}
}
public static void main(String[] argv) {
System.out.println(Os.exec2("ls -Fla /"));
}
}https://stackoverflow.com/questions/59958413
复制相似问题