Java execute command line program #39;find#39; returns error(Java执行命令行程序find返回错误)
问题描述
以下从终端工作没问题
find testDir -type f -exec md5sum {} ;
其中 testDir
是包含一些文件(例如 file1、file2 和 file3)的目录.
Where testDir
is a directory that contains some files (for example file1, file2 and file3).
但是,我在 Java 中使用以下内容时遇到错误
However, I get an error using the following in Java
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("find testDir -type f -exec md5sum {} \;");
错误是
find: missing argument to `-exec'
我相信我正确地转义了字符.我尝试了几种不同的格式,但我无法让它工作.
I believe I am escaping the characters correctly. I have tried several different formats and I cannot get this to work.
更新 @jtahlborn 完美地回答了这个问题.但是该命令现在略有更改,以便在计算 md5sum 之前对目录中的每个文件进行排序,如下所示(我已经接受了原始问题的出色答案,所以如果他们能提出格式,我会买啤酒为此.我已经尝试了我能想到的所有组合,但没有成功.)
UPDATE @jtahlborn answered the question perfectly. But the command has now changed slightly to sort each file in the dir before calculating the md5sum and is as follows (I have already accepted the excellent answer for the original question so I'll buy somebody a beer if they can come up with the format for this. I have tried every combination I can think of following the answer below with no success.)
"查找 testDir -type f -exec md5sum {} + | awk {print $1} | sort |md5sum ;"
"find testDir -type f -exec md5sum {} + | awk {print $1} | sort | md5sum ;"
新更新
对于管道,你需要一个 shell,所以我最终得到了这个,它工作得很好,你仍然可以获得输出.
For pipe, you need a shell so I ended up with this, which works great and you can still get the output.
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[]
{
"sh", "-l", "-c", "find " + directory.getPath() + " -type f -exec md5sum {} + | awk '{print $1}' | sort | md5sum"
});
推荐答案
使用多参数调用 exec (否则你会被转义规则咬住).此外,由于您不是从 shell 脚本调用,因此您不需要转义分号:
use the multi-argument call to exec (otherwise you can get bitten by escape rules). also, since you aren't calling from a shell script, you don't need to escape the semicolon:
Process pr = rt.exec(new String[]{"find", "testDir", "-type", "f", "-exec", "md5sum", "{}", ";"});
这篇关于Java执行命令行程序'find'返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java执行命令行程序'find'返回错误
基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01