java: 在程序中编译和执行java程序

编译Java程序:

import java.io.FileNotFoundException;

import java.io.PrintWriter;


import com.sun.tools.javac.Main;


public class Test {

    public static void main(String[] argv) throws FileNotFoundException {

        PrintWriter writer = new PrintWriter("result.txt");

        String[] options = { "/Users/Biao/Desktop/FilteredJList.java" };

        Main.compile(options, writer);

    }

}

执行Java程序:

// Process proc = Runtime.getRuntime().exec(String.format("java %s", "FilteredJList"));

    private void run(String directoryString classNameString[] args) {

        try {

            File classLoaderDirectory = new File(directory);

            URL url = classLoaderDirectory.toURL();

            URL[] urls = new URL[] { url };

            ClassLoader loader = new URLClassLoader(urls);


            Class clazz = loader.loadClass(className);


            Method mainMethod = clazz.getMethod("main"String[].class);

            // mainMethod.invoke(null, new Object[] { new String[] { /* args */}

            // });

            mainMethod.invoke(nullnew Object[] { args });

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

================================分隔线================================

 

JDK6.0中可以使用下面的方法:

This example using the Java Compiler API introduced in JDK 1.6 to programmatically compile a Java class. Here we'll compile the Hello.java. The process of compiling can be start by obtaining a JavaCompiler from the ToolProvider.getSystemJavaCompiler().

The simplest way to compile is by calling the run() method of the compiler and passing the first three arguments with null value. These three argument will use the default System.in,System.out and System.err. The final parameter is the file of the Java class to be compiled.

When error happened during compilation process the non-zero result code will be returned. After the compile process you'll have the Hello.class just as if you were compiling using thejavac command.

package org.kodejava.example.tools;
 
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
 
public class CompileHello {
public static void main(String[] args) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null,
"src/org/kodejava/example/tools/Hello.java");
 
System.out.println("Compile result code = " + result);
}
}
或者:Runtime run=Runtime.getRuntime(); 
run.exec("cmd /c javac Calculator.java"); 
run.exec("cmd /c java Calculator"); 
Calculator是个有界面的程序,为什么编译成功,却运行不出来? 
Calculator程序文件在当前程序的目录文件中的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值