import java.io.*; //use this thread to evaluate java class file public class RunJava extends Thread { public static final int FIVE_SECONDS = 5000; private Process p = null; // added in for java sandbox security control private String cmd = "java -Djava.security.manager -Djava.security.policy==\"E:/Program Files/WampServer/gradingsystem/gspolicy\" -classpath "; private File txt = null; public RunJava(String classDir, String classname, String outputDir){ cmd = cmd +"\"" + classDir + "\" " + classname; System.out.println(cmd); txt = new File(outputDir + "/" + classname + "_RunOutput.txt"); try{ if(!txt.exists()) txt.createNewFile(); } catch(Exception e){ System.err.println(e.getMessage()); } } public void run(){ Runtime jRun = Runtime.getRuntime(); try { p = jRun.exec(cmd); //get input stream, and write content to output file BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(txt))); StringBuilder sb = new StringBuilder(""); String s = ""; while ((s = br.readLine()) != null) sb.append(s); pw.print(sb.toString()); pw.close(); p.waitFor(); } catch (Exception e) { System.err.println(e.getMessage()); } } public void killThread(){ //kill RunJava, and delete output file p.destroy(); if (txt.exists()) txt.delete(); } public static void main(String[] args) { //take input string from outside String classDir = args[0]; String classname = args[1]; String outputDir = args[2]; //for debug /*System.out.println("classDir: " + classDir); System.out.println("classname: " + classname); System.out.println("outputDir: " + outputDir);*/ try { //Start a new thread RunJava run = new RunJava(classDir, classname, outputDir); run.start(); //limit running time long start = System.currentTimeMillis(); long end = start + FIVE_SECONDS; do{ Thread.sleep(100); if(System.currentTimeMillis()> end) run.killThread(); } while(run.getState().toString().equals("RUNNABLE")); System.out.println("Program Finished!"); } catch (Exception e) { System.err.println(e.getMessage()); } } }
Sunday, September 25, 2011
Java program for Running System command (test one)
使用java 去compile文件再执行local file
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment