[英]Using Java Runtime class to find out a class in Jar file in Unix
我正在使用Java Runtime类编写一个程序,该程序检查jar文件列表中的类文件。 这是我的程序:
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
Process p = Runtime.getRuntime().exec("find /home/user/lib/ -name \"*.jar\" | xargs grep MyClass.class");
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..");
e.printStackTrace();
System.exit(-1);
}
}
}
当我运行该程序时,我收到以下错误消息:
Here is the standard output of the command:
Here is the standard error of the command (if any):
**find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]**
如果我直接运行命令find /home/user/lib/ -name \\"*.jar\\" | xargs grep MyClass.class");
,请帮助我这段代码中缺少的内容find /home/user/lib/ -name \\"*.jar\\" | xargs grep MyClass.class");
find /home/user/lib/ -name \\"*.jar\\" | xargs grep MyClass.class");
在我的UNIX命令行上,它工作正常。
另外,如果我用下面的行替换表达式,则我的Java代码运行良好。
Process p1 = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "cd /home/user/lib/ && find . -name \"*.jar\" | xargs grep MyClass.class" });
Process p = Runtime.getRuntime().exec("find /home/user/lib/ -name \"*.jar");
更改为
Process p = Runtime.getRuntime().exec("sh -c find /home/user/lib/ -name \"*.jar");
以便外壳程序参与并扩展通配符。
但是,您实际上并不需要在这里运行find
,您可以自己使用递归调用的Files.listFiles()
。
我也很想知道您接下来要做什么。 我可以通过定义一个用该JAR列表初始化的URLClassLoader
,然后使用它来尝试加载该类,而不是自己解压缩所有JAR来做到这一点。
如果所有罐子都在类路径上:
Class<?> klazz = Class.forName("sun.security.ec.SunEC", false,
ClassLoader.getSystemClassLoader());
CodeSource codeSource = klazz.getProtectionDomain().getCodeSource();
URL url = codeSource.getLocation();
System.out.println(url.toExternalForm());
file:/C:/Program%20Files/Java/jre7/lib/ext/sunec.jar
参加的细节: false
表示不进行任何班级初始化。
否则 ,仅使用文件列表,则可以使用JarFile。 在Java 8中,您甚至可以使用并行性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.