运行外部Java程序

如何运行外部Java文件,有三种方式。

首先先写一个java文件到c盘中:

public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String str = "public class Hello { public static void main(String[] args) {System.out.println(\"hello!\");}}";
        File myDir = new File("C:\\Users\\whatsoooever\\Desktop\\hello");
        myDir.mkdir();
        File file = new File("C:\\Users\\whatsoooever\\Desktop\\hello\\Hello.java");
        FileWriter fw = new FileWriter(file);
        fw.write(str);
        fw.flush();
        fw.close();
	}
}
  • 第一种运行方式:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null,
                "C:\\Users\\whatsoooever\\Desktop\\hello\\Hello.java");
System.out.println(result == 0 ? "编译成功" : "编译失败");
  • 第二种运行方式,启动另一个进程执行(需要有class文件):
Runtime runtime = Runtime.getRuntime();
//格式为:"java -cp  " + dir + " " + classFile
Process process = runtime.exec("java  -cp  c:\\Users\\whatsoooever\\Desktop\\hello    Hello");

//把另一个进程中的内容读进来
InputStream in = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String info = "";
while ((info = br.readLine()) != null) {
      System.out.println(info);
 }
  • 第三种方式,反射:
//格式:"file:/"+dir
URL[] urls = new URL[]{new URL("file:/C:\\Users\\whatsoooever\\Desktop\\hello\\")};
URLClassLoader loader = new URLClassLoader(urls);
//loadClass方法的参数是className
Class c = loader.loadClass("Hello");
//调用main方法
Method m = c.getMethod("main", String[].class);
m.invoke(null, (Object) new String[]{});

注意最后m.invoke(null, (Object) new String[]{});这边有个强转!

发布了41 篇原创文章 · 获赞 9 · 访问量 9835

猜你喜欢

转载自blog.csdn.net/Serena0814/article/details/105302735