我正在尝试从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();
}
提前致谢。
答案 0 :(得分:0)
谢谢大家,特别是@RealSkeptic和@ qingl97。根据您的建议,我进行了一些小改动,并且有效。
Process p = Runtime.getRuntime().exec(
new String[]{"sh","-c",command});
p.waitFor()
答案 1 :(得分:0)
如果您想获得输出,请尝试此操作。 ProcessBuilder对于多个参数和commans来说会更好
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);
}
答案 2 :(得分:0)
正如RealSkeptic指出的那样,管道字符(|
)不是命令参数;它们是由shell解释的。并且您直接调用命令(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);
}