Java:从Java代码执行shell命令无效

Java:从Java代码执行shell命令无效,java,cmd,Java,Cmd,我试图从java代码运行此命令,并希望生成一个包含1个线性代码的文件: cut -d , -f 2 /online/data/test/output/2Zip/brita_ids-*.csv | sort -u | tr -d '\n' | sha512sum > /online/data/test/output/file_name.txt 当我从cmd行运行时,这个cmd很好,但是我的java代码有一些问题,我花了很长时间才弄清楚,并且没有看到生成预期的文件有线索知道这里发生了什么吗

我试图从java代码运行此命令,并希望生成一个包含1个线性代码的文件:

cut -d , -f 2  /online/data/test/output/2Zip/brita_ids-*.csv | sort -u | tr -d '\n' | sha512sum > /online/data/test/output/file_name.txt
当我从cmd行运行时,这个cmd很好,但是我的java代码有一些问题,我花了很长时间才弄清楚,并且没有看到生成预期的文件有线索知道这里发生了什么吗?

以下是生成该文件的代码:

public String executeCommand(String command) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        LOG.info( "Executing cmd : " + command  );
        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();
        LOG.error( "Error in executing cmd : " + command + " \nError : " + e.getMessage() );
    }

    return output.toString();

}

提前谢谢。

谢谢大家,特别是@realpointist和@qingl97。根据您的建议,我做了一个小改动,效果不错

Process p = Runtime.getRuntime().exec(
          new String[]{"sh","-c",command});

 p.waitFor()

如果您还想获得输出,请尝试此操作。ProcessBuilder更适合于多个参数和逗号

 try {
        Process process = Runtime
                .getRuntime()
                .exec("cut -d , -f 2  /online/data/test/output/2Zip/brita_ids-*.csv | sort -u | tr -d '\n' | sha512sum > /online/data/test/output/file_name.txt");
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            // print the output to Console
            System.out.println(line);
            line = reader.readLine();
        }

    } catch (Exception e1) {
        e1.printStackTrace();
    } 
    System.out.println("Finished");
如果您需要一系列命令,请执行类似的操作

 ProcessBuilder builder = new ProcessBuilder(
        "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while (true) {
        line = r.readLine();
        if (line == null) { break; }
        System.out.println(line);
    }

正如Real怀疑论者指出的那样,管道字符(
|
)不是命令参数;它们由一个外壳来解释。您直接调用命令(
cut
),而不是使用shell

这不是对您问题的直接回答,但您可以在不使用任何shell命令的情况下完成任务:

Charset charset = Charset.defaultCharset();
MessageDigest digest = MessageDigest.getInstance("SHA-512");

try (DirectoryStream<Path> dir = Files.newDirectoryStream(
        Paths.get("/online/data/test/output/2Zip"), "brita_ids-*.csv")) {

    for (Path file : dir) {
        Files.lines(file, charset)
            .map(line -> line.split(",")[1])
            .sorted(Collator.getInstance()).distinct()
            .forEach(value -> digest.update(value.getBytes(charset)));
    }
}

byte[] sum = digest.digest();

String outputFile = "/online/data/test/output/file_name.txt";
try (Formatter outputFormatter = new Formatter(outputFile)) {
    for (byte sumByte : sum) {
        outputFormatter.format("%02x", sumByte);
    }
    outputFormatter.format(" *%s%n", outputFile);
}
Charset Charset=Charset.defaultCharset();
MessageDigest=MessageDigest.getInstance(“SHA-512”);
try(DirectoryStream dir=Files.newDirectoryStream(
get(“/online/data/test/output/2Zip”),“brita_id-*.csv”)){
for(路径文件:dir){
Files.lines(文件,字符集)
.map(直线->直线分割(“,”[1])
.sorted(Collator.getInstance()).distinct()
.forEach(value->digest.update(value.getBytes(charset));
}
}
字节[]总和=摘要。摘要();
字符串outputFile=“/online/data/test/output/file_name.txt”;
try(格式化程序outputFormatter=新格式化程序(outputFile)){
for(字节sumByte:sum){
outputFormatter.format(“%02x”,sumByte);
}
outputFormatter.format(“*%s%n”,outputFile);
}

您遇到的错误是什么?最好1)使用ProcessBuilder,2)为您的命令使用字符串集合,而不是单个字符串。请注意,您没有显示如何调用此方法。@patty使用
getErrorStream()
读取错误。请向我们显示
命令的值。如果可能,尝试将其打印到控制台。它应该与您在使用console时使用的文本完全相同。您使用的是shell语法(管道、星号),但显然您并没有在shell中运行它,因此所有这些都被认为是命令的文本参数。你应该在一个实际的shell中运行它。空的catch块是非常糟糕的做法。你真的需要从SO复制代码并在没有编辑的情况下使用吗?太糟糕了。非常可怕