如题,java操作shell命令,在指定目录下生成一个文本,并添加内容。请问这个怎么操作
1条回答 默认 最新
allway2 2021-01-29 11:53关注import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {try {
//Run a bat file
Process process = Runtime.getRuntime().exec(
"cmd /c echo test>c:\\test.txt");StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报