简单java在线测评程序
简单java程序在线测评程序
一.前言
大家过年好!今年的第一篇博客啊!家里没有网,到处蹭无线!日子过得真纠结!因为毕设的需求,简单写了一个java程序在线测评程序,当然也可以在本地测试。
二.思路
首先简单介绍一下思路:
1.得到java程序的源代码,不需要导入包。得到源码之后在前面加入”import java.util.*;”
2.通过JavaCompiler对象可以帮助我们将java源代码编译成class文件。
3.通过DiagnosticCollector对象可以获得编译过程中产生的编译信息。
4.通过StandardJavaFileManager对象管理生成的class文件,例如文件的存放位置。
5.StringSourceJavaObject对象可以对java源码进行包装并处理。
数据是控制台输入的,所以要重定向System.in(注意保存标准的输入流);另外程序的输出是到标准的输出流的,为了获得输出结果,我的方法是重定向输出流到ByteArrayOutputStream,然后利用ByteArrayOutputStream构造BufferedReader。
6.运行程序,通过java的反射机制,获得main函数的Method对象。
7.运行时间的计算: 通过System.currentTimeMillis()方法。
8.程序所需内存: 通过Runtime的freeMemory()方法。
9.异常信息的获取:StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); sw.toString();
三.问题解决
1. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 出现NullPointerException。
查看部分源码如下:
private static final String[] defaultToolsLocation = { "lib", "tools.jar" };
private Class<?> findSystemToolClass(String toolClassName)
throws MalformedURLException, ClassNotFoundException {
// try loading class directly, in case tool is on the bootclasspath
try {
return Class.forName(toolClassName, false, null);
} catch (ClassNotFoundException e) {
trace(FINE, e); // if tool not on bootclasspath, look in default tools location (tools.jar)
ClassLoader cl = (refToolClassLoader == null ? null : refToolClassLoader.get());
if (cl == null) {
File file = new File(System.getProperty("java.home"));
if (file.getName().equalsIgnoreCase("jre"))
file = file.getParentFile();
for (String name : defaultToolsLocation)
file = new File(file, name); // if tools not found, no point in trying a URLClassLoader
// so rethrow the original exception.
if (!file.exists())
throw e; URL[] urls = { file.toURI().toURL() };
trace(FINE, urls[0].toString()); cl = URLClassLoader.newInstance(urls);
refToolClassLoader = new WeakReference<ClassLoader>(cl);
} return Class.forName(toolClassName, false, cl);
}
}
打印 System.out.println(System.getProperty("java.home")); 如下:
C:\Program Files (x86)\Java\jre6
defaultToolsLocation = { "lib", "tools.jar" }; 也就是最终到
C:\Program Files (x86)\Java\jre6\lib\tools.jar中寻找tools.jar
然而jre6\lib中没有tools.jar, 而是在C:\Program Files (x86)\Java\jdk\lib中。最直接的办法就是将它复制进去就行了。
2.异常信息的获取。
3.输入流和输出流的重定向。
详细内容请看代码!
四.代码
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider; public class CompileAndRunJavaFile {
public static void main(String[] args) {
StringBuilder code = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(new File("测试程序地址")));
String content;
while((content = br.readLine()) != null){
code.append(content).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
CompileAndRunJavaFile cr = new CompileAndRunJavaFile();
cr.compileAndRunJavaFile(code.toString());
if(cr.isCompileAndRunOK()) {
System.out.println("运行时间: " + cr.getUseTime() + "ms");
System.out.println("内存使用: " + cr.getUseMemory() + "kb9");
System.out.println("运行结果: \n" + cr.getOutMsg());
} else if(cr.isCompilerError()) {
System.out.println("编译错误: " + cr.getCE());
} else if(cr.isRunningError()) {
System.out.println("运行错误: " + cr.getError());
}
}
//编译错误
private StringBuilder ce = new StringBuilder();
public String getCE(){
return ce.toString();
} //内存使用
private double useMemory = 0.0;
public double getUseMemory(){
return useMemory;
} //运行时间
private long useTime = 0;
public long getUseTime(){
return useTime;
}
//输出信息
private StringBuilder outMsg = new StringBuilder();
public String getOutMsg(){
return outMsg.toString();
}
//异常信息
private String error = null;
public String getError(){
return error;
}
//是否正常编译并运行
private boolean isCompileAndRunOK = false; public boolean isCompileAndRunOK(){
return isCompileAndRunOK;
} //程序的运行时间, 单位:ms
private int limitTime = 2000;
//程序所占内存, 单位 :KB
private double limitMemory = 256000.0; public void setLimitTime(int limitTime){
this.limitTime = limitTime;
} public void setLimitMemory(double limitMemory){
this.limitMemory = limitMemory;
} //是否为编译错误
private boolean isCompilerError = false;
public boolean isCompilerError(){
return isCompilerError;
} //是否为运行错误
private boolean isRunningError = false;
public boolean isRunningError(){
return isRunningError;
} private static final String className = "Main";
private static final String methodName = "main";
private String getClassOutput(){
//设置class文件的存放位置
if(System.getProperty("java.class.path").contains("bin")) return "bin/";
else return "./";
} private void compileAndRunJavaFile(String code){
PrintStream ps = null;
FileInputStream fis = null;
BufferedReader br = null;
//保存标准输出流
InputStream stdIn = System.in;
//保存标准输入流
PrintStream stdOut = System.out; //为源代码导入默认的包
code = "import java.util.*;\n" + code;
try {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// define the diagnostic object, which will be used to save the
// diagnostic information
DiagnosticCollector<JavaFileObject> oDiagnosticCollector = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(oDiagnosticCollector, null, null);
// set class output location
fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File[] { new File(getClassOutput()) })); StringSourceJavaObject sourceObject = new CompileAndRunJavaFile.StringSourceJavaObject(className, code);
Iterable<? extends JavaFileObject> fileObjects = Arrays.asList(sourceObject);
CompilationTask task = compiler.getTask(null, fileManager, oDiagnosticCollector, null, null, fileObjects);
boolean result = task.call(); if (result) {
Runtime runtime = Runtime.getRuntime();
Class<?> clazz = Class.forName(className);
Method method = clazz.getMethod(methodName, new Class<?>[]{String[].class}); //重置输入流, 需要存放数据文件的文件名
fis = new FileInputStream(new File("数据文件地址"));
System.setIn(fis);
//重置输出流,需要获得控制台的输出
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ps = new PrintStream(bao);
System.setOut(ps); long startFreeMemory = runtime.freeMemory();//Java 虚拟机中的空闲内存量
//执行时间也是无法知道,因为dos执行java命令,程序无法知道它到底执行到那里了,两个进程,互不了解
long startCurrentTime = System.currentTimeMillis();//获取系统当前时间
method.invoke(null, new Object[]{null});
long endCurrentTime = System.currentTimeMillis();
long endFreeMemory = runtime.freeMemory();
//内存的使用情况,不是很精确
useMemory = (startFreeMemory-endFreeMemory)/1024.0;
if(useMemory > limitMemory) throw new Exception("Out Limit Memory!");
useTime = endCurrentTime-startCurrentTime;
if(useTime > limitTime) throw new Exception("Time Limited!"); //获得控制台的输出
br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bao.toByteArray())));
String outc = null;
while((outc = br.readLine()) != null)
outMsg.append(outc).append("\n");
//正常编译并运行
isCompileAndRunOK = true;
} else {
isCompilerError = true;
//打印编译的错误信息
Pattern p = Pattern.compile("Main.java\\D*(\\d+):", Pattern.DOTALL);
for (Diagnostic<? extends JavaFileObject> oDiagnostic : oDiagnosticCollector.getDiagnostics()){
/*信息示例:
Compiler Error: Main.java:8: 找不到符号
符号: 类 Scanner
位置: 类 Main
*/
//将行号减1
Matcher m = p.matcher("Compiler Error: " + oDiagnostic.getMessage(null));
if(m.find()) {
ce.append(m.replaceAll("Main.java " + String.valueOf(Integer.valueOf(m.group(1))-1)) + ":").append("\n");
} else {
ce.append("Compiler Error: " + oDiagnostic.getMessage(null)).append("\n");
}
}
} } catch (Exception e) {
isRunningError = true;
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
Pattern p = Pattern.compile("Main.java\\D*(\\d+)", Pattern.DOTALL);
Matcher m = p.matcher(sw.toString());
if(m.find()){
error = m.replaceAll("Main.java " + String.valueOf(Integer.valueOf(m.group(1))-1) + ":");
} else {
error = sw.toString();
}
} finally {
//关闭流
try {
if(fis != null)
fis.close();
if(ps != null)
ps.close();
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
//恢复输入输出流
System.setIn(stdIn);
System.setOut(stdOut);
}
} private class StringSourceJavaObject extends SimpleJavaFileObject {
private String content = null;
public StringSourceJavaObject(String name, String content) {
super(URI.create(name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
}
五.运行结果显示
1.正常运行
运行时间: 16ms
内存使用: 225.5546875kb
运行结果:
5 4 3 2 1
2.编译错误
编译错误: Compiler Error: Main.java 8 找不到符号
符号: 类 Scanner
位置: 类 Main:
Compiler Error: Main.java 8 找不到符号
符号: 类 Scanner
位置: 类 Main:
3.运行错误
(1)运行错误: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.test.CompileAndRunJavaFile.compileAndRunJavaFile(CompileAndRunJavaFile.java:163)
at com.test.CompileAndRunJavaFile.main(CompileAndRunJavaFile.java:44)
Caused by: java.lang.StackOverflowError
at Main.fun(Main.java 4:)
at Main.fun(Main.java 4:)
(2)运行错误: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.test.CompileAndRunJavaFile.compileAndRunJavaFile(CompileAndRunJavaFile.java:163)
at com.test.CompileAndRunJavaFile.main(CompileAndRunJavaFile.java:44)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 6
at Main.main(Main.java 18:)
... 6 more
六.测试程序
public class Main {
public static void fun(){
fun();
}
public static void main(String[] args) { Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] array = new int[n];
for(int i=0; i<n; ++i)
array[i] = scan.nextInt(); for(int i=0; i<n; ++i)
System.out.print(array[i] + " ");
System.out.println(); //array[n+1] = 0;
//fun();
} }
简单java在线测评程序的更多相关文章
- 简单java web应用程序搭建与部署
1. 准备工作 工具:tomcat.editplus.jdk.windows操作系统 操作:在windows操作系统上安装jdk.tomcat.editplus,配置JAVA_HOME,Path,CL ...
- 输出多行字符的一个简单JAVA小程序
public class JAVA { public static void main(String[] args) { System.out.println("-------------- ...
- 【java学习】Servlet简单的表单程序(一)
此文用于java学习,在此小记. 在此小Demo中使用到了Servlet,所以有必要了解一下Servlet的相关知识.(Servlet的相关知识摘抄自http://blog.csdn.net/jiuq ...
- 简单的java Hadoop MapReduce程序(计算平均成绩)从打包到提交及运行
[TOC] 简单的java Hadoop MapReduce程序(计算平均成绩)从打包到提交及运行 程序源码 import java.io.IOException; import java.util. ...
- JAVA基础——最简单的多重循环程序
Java 循环语句之多重循环 循环体中包含循环语句的结构称为多重循环.三种循环语句可以自身嵌套,也可以相互嵌套,最常见的就是二重循环.在二重循环中,外层循环每执行一次,内层循环要执行一圈. 如下所示: ...
- java编写简单的语法分析预测程序
编译原理课程中,编了一个简单的语法分析预测程序,这个程序时根据固定的文法得到预测分析表,然后编写程序来判断表达式是否会正确推到出来. 前提是程序没有左递归符合LL(1)文法: 文法如下: E→TE' ...
- 使用eclipse创建一个简单的Java Web应用程序
关于Java JDK/JRE.Tomcat的配置等等都没什么好说的,主要记录一下使用Eclipse创建web工程时的一些点以及说一说自己用IDEA的创建失败的过程(IDEA没运行成功...暂时不想弄了 ...
- 【转】java线上程序排错经验2 - 线程堆栈分析
前言 在线上的程序中,我们可能经常会碰到程序卡死或者执行很慢的情况,这时候我们希望知道是代码哪里的问题,我们或许迫切希望得到代码运行到哪里了,是哪一步很慢,是否是进入了死循环,或者是否哪一段代码有问题 ...
- Java全栈程序员之04:Ubuntu下安装MySQL、注册服务及Navcat
在安装MySQL之前,我们先来介绍一下Ubuntu下软件的安装方式.首先回顾下,我们安装JDK,使用的是后缀名为tar.gz的安装包.安装idea,使用的是tar.gz:那有没有别的安装方式呢? 1. ...
随机推荐
- github for windows 安装 使用
遇到无数的未知问题.光是安装就搞了好久. 安装程序显示安装了.NET Framework4.5,然后提示重启.重启后,自动开始下载文件,最多到2%就走不动了. 后来请求了下面这个链接,才开始下载了(虽 ...
- iOS开发资源(持续更新)
vm10虚拟机安装Mac OS X10.10教程 马上着手开发 iOS 应用程序 (Start Developing iOS Apps Today) Xcode使用教程详细讲解 (上) Xcode使用 ...
- Java的四种引用方式
一.引用基本概念 从JDK1.2版本开始,把对象的引用分为四种级别,从而使程序能更加灵活的控制对象的生命周期.这四种级别由高到低依次为:强引用.软引用.弱引用.虚引用. 1.强引用(StrongRef ...
- 复习排序with javascript
最近又翻看了一下数据结构(数据结构学渣). 以前总是看不懂,连冒泡和选择排序都要纠结半天,后来才慢慢有意识能区分开来. 当真的理解了快速排序之后,才觉得,这是个很赞的排序,很容易理解. 于是简单的,模 ...
- 【Beta】Daily Scrum Meeting第二次
1.任务进度 学号 已完成 接下去要做 502 系负责人及所负责专业的表 写出PHP测试的demo:将okHttp的请求放在非UI线程中执行 509 PHP更该用户信息:更新系负责人所负责系:删除任务 ...
- java-String Date Calendar之间的转换
1.Calendar 转化 String Calendar calendat = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDa ...
- SQL执行效率1
第一种方法:使用insert into 插入,代码如下: ? 1 2 3 4 5 6 7 $params = array('value'=>'50′); set_time_limit(0); e ...
- 基于Picture Library创建的图片文档库中的上传多个文件功能(upload multiple files)报错怎么解决?
复现过程 首先,我创建了一个基于Picture Library的图片文档库,名字是 Pic Lib 创建完毕后,我点击它的Upload 下拉菜单,点击Upload Picture按钮 在弹出的对话框中 ...
- ASP.net之策略模式
设计思路: 用ASP.net设计,调用策略模式.在第一个数和第二个数的文本框中输入数值,单击录题按钮,数值保存在n1,n2文档中,把要做的题都保存完后,单击开始按钮,开始做题,做完单击判断按钮,进行判 ...
- IOS9.0中hash值的bug与解决方案
事件起因 事情是这样的:产品上线发布,突然出现了问题.运营Gg过来反应,当场给露珠演示,运营同事的手机是iphone,bug确实是存在的.奇怪的是露珠用了其他iphone手机(借别人的,露珠的是吊死安 ...