使用Java程序执行cat命令不能按预期工作

3

我试图在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);
1个回答

0
我找到了一个相关问题。为了总结那里找到的一些有用的东西,文件重定向需要一个shell,但exec没有shell上下文。幸运的是,您可以使用ProcessBuilder执行带有重定向的进程。对于您的情况,它看起来应该像这样:
public static void main(String[] args) 
{

    try{            
        ProcessBuilder builder = new ProcessBuilder("cat", "file1","file2");
        File combinedFile = new File("combinedFile");
        builder.redirectOutput(combinedFile);
        builder.redirectError(combinedFile);
        Process p = builder.start();
    } catch(IOException e){
        //handle exception...
    }

}

注意:当调用redirectErrorredirectOutput时,您可能会收到一个错误,指出找不到该符号。如果您正在编译Java 1.7之前的版本,则会发生这种情况,因为1.7是引入这些方法的版本。 如果可以升级您的Java,则可以消除此错误。
如果无法升级Java,则以下代码将起作用:
public static void main(String[] args) 
{

    try{            
        ProcessBuilder builder = new ProcessBuilder("cat", "file1","file2");
        File combinedFile = new File("combinedFile");
        Process p = builder.start();

        InputStream isFromCat = p.getInputStream();
        OutputStream osCombinedFile = new FileOutputStream(combinedFile);

        byte[] buffer = new byte[1024];
        int read = 0;
        while((read = isFromCat.read(buffer)) != -1) {
            osCombinedFile.write(buffer, 0, read);
        }

    } catch(IOException e){
        //handle exception...
    }

}

值得注意的是,通过系统调用cat来合并Java文件不是最优秀的方式。我一直认为这只是一个代表更复杂用例的玩具案例。如果你真的只想要合并两个文件,那么你应该编写代码来避免系统调用,只需将两个文件作为输入流读取,然后将它们写入结果文件即可。如果你在弄清楚这个过程中遇到了问题,这些细节肯定属于另一个问题。


@PepperBoy 好的,我也调整了我的答案。你正在使用哪个版本的Java进行编译? - augray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接