如果它只是 Unix,您可以使用该locate
命令。不过,不要忘记updatedb
定期运行(最好是自动运行)。
要在 Java 中实际运行命令行命令,请查看这篇文章。基本命令是Runtime#exec
,但您需要进行一些错误检查。文章中提供的片段是:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
Process p = Runtime.getRuntime().exec("ps -ef");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
否则,您可以遍历文件树(使用 NIO.2 的 Java 本机)。不过,这可能需要更长的时间,因为它没有被缓存。