从Java调用GnuWin命令,还是有更好的方法?
我需要知道文件列表中是否包含特定字符串。文件列表是动态的,我必须检查字符串的动态列表。这必须在Java中完成,才能处理结果(true或false)。微软视窗也是一项要求 我考虑过这个问题,我尝试使用unix方法来实现这一点:从Java调用GnuWin命令,还是有更好的方法?,java,runtime,Java,Runtime,我需要知道文件列表中是否包含特定字符串。文件列表是动态的,我必须检查字符串的动态列表。这必须在Java中完成,才能处理结果(true或false)。微软视窗也是一项要求 我考虑过这个问题,我尝试使用unix方法来实现这一点: find C:/temp | xargs grep import -sl 使用GnuWin,这在cmd中工作没有任何问题。所以我试着把它转换成Java语言。我读了很多关于使用运行时类和ProcessBuilder类的文章。但这些技巧都不管用。最后,我尝试了以下两段代码:
find C:/temp | xargs grep import -sl
使用GnuWin,这在cmd中工作没有任何问题。所以我试着把它转换成Java语言。我读了很多关于使用运行时类和ProcessBuilder类的文章。但这些技巧都不管用。最后,我尝试了以下两段代码:
String binDir = "C:/develop/binaries/";
List<String> command = new ArrayList<String>();
command.add("cmd");
command.add("/c");
command.add(binDir+"find");
command.add("|");
command.add(binDir+"xargs");
command.add(binDir+"grep");
command.add("import");
command.add("-sl");
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("C:/temp"));
final Process proc = builder.start();
printToConsole(proc.getErrorStream());
printToConsole(proc.getInputStream());
int exitVal = proc.waitFor();
我还尝试了许多其他方法来执行该命令,但要么我收到一条错误消息(例如,找不到文件),要么进程再也不会返回
我的问题是:
1.你知道做这项工作的更好方法吗?
2.如果没有:您是否看到代码中有任何错误?
3.如果没有:您是否有其他方法让我尝试运行该命令
提前谢谢。在我的脑海里:
File yourDir = new File("c:/temp");
File [] files = yourDir.listFiles();
for(File f: files) {
FileInputStream fis = new FileInputStream(f);
try {
BuffereReaded reader = new BufferedReader(new InputStreamReader(fis,"UTF-8")); // Choose correct encoding
String s;
while(((s=reader.readLine())!=null) {
if (s.contains("import"))
// Do something (add file to a list, for example). Possibly break out the loop
}
} finally {
if (fis!=null)fis.close();
}
}
Java对子进程的支持非常弱,尤其是在Windows上。如果您真的不需要,请避免使用该API
相反,讨论如何替换递归搜索的
find
,并且grep
应该足够简单(尤其是有帮助)。我在第一次尝试时没有看到您的strDir。这是打字错误吗?不是,第二个的strDir是由builder.directory(新文件(“C:/temp”))设置的代码>在第一个中。你不是混淆了strDir和binDir吗?无论如何,就个人而言,我更愿意尝试使用Java代码来实现这一点,如果需要的话,还可以使用Java库/框架来实现与cmd相同的功能。虽然我喜欢Unix命令power,但您编写的代码不是很健壮,也不是很好移植。是的,我没有正确理解您的问题。现在我修正了我的评论。:)我想把所有的文件都读入java,用“手工”搜索。但是文件列表可以包含数百或数千个文件。你知道POSIXfind
在默认情况下是递归的吗?@DonalFellows是:-)这只是一小段代码来说明我是如何做到这一点的。我认为使用递归方法没有那么困难。
File yourDir = new File("c:/temp");
File [] files = yourDir.listFiles();
for(File f: files) {
FileInputStream fis = new FileInputStream(f);
try {
BuffereReaded reader = new BufferedReader(new InputStreamReader(fis,"UTF-8")); // Choose correct encoding
String s;
while(((s=reader.readLine())!=null) {
if (s.contains("import"))
// Do something (add file to a list, for example). Possibly break out the loop
}
} finally {
if (fis!=null)fis.close();
}
}