我试图在Java程序中使用cat命令将两个文件合并成一个。包含cat命令的代码行会将file1和file2两个文件写入一个名为combinedfile的第三个文件。但是,我观察到的是,程序没有创建这个文件(combinedfile),而是仅在终端上显示输出。
我该如何确保两个文件确实被复制到了第三个文件中?
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellCommand
{
public static void main(String[] args)
{
ExecuteShellCommand obj = new ExecuteShellCommand();
String command = "cat file1 file2 > combinedfile";
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command)
{
StringBuffer output = new StringBuffer();
Process p;
try
{
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null)
{
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
编辑:
我尝试了建议使用的ProcessBuilder,但是我收到了这个错误。 代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.*;
import java.util.*;
public class ExecuteShellCommand
{
public static void main(String[] args)
{
try
{
ProcessBuilder builder = new ProcessBuilder("cat", "/home/PepperBoy/Desktop/file1.txt","/home/PepperBoy/Desktop/file2.txt");
File combinedFile = new File("/home/PepperBoy/Desktop/file3.txt");
builder.redirectOutput(combinedFile);
builder.redirectError(combinedFile);
Process p = builder.start();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
错误
ExecuteShellCommand.java:14: cannot find symbol
symbol : method redirectOutput(java.io.File)
location: class java.lang.ProcessBuilder
builder.redirectOutput(combinedFile);