首页>代码>Java代码在线编译运行项目实例>/项目/源码/comilper/src/main/java/com/online/common/WebJavaRunner.java
package com.online.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WebJavaRunner {
	
	private String in;
	private String classPath;
	private String name;
	private boolean isInput;
	private int timeout = 3000;

	public  List<String> executor() {
		String[] command = new String[] { "java", "-cp", classPath, name };
		ProcessBuilder build = new ProcessBuilder(command);
		if (isInput) {
			build.redirectInput(new File(in));
		}
		build.redirectErrorStream(true);
		Process p = null;
		try {
			p = build.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return readLinesByProcess(p);
	}
	
	private List<String>  readLinesByProcess(Process process){
		String line = null;
		BufferedReader br = null;
		Timer timer = new Timer();
		List<String> list = new ArrayList<String>();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(process.isAlive()) {
					process.destroy();
				}
			}
		}, timeout);
		try {
			br = new BufferedReader(
					new InputStreamReader(process.getInputStream(),"gbk"));
			while ((line = br.readLine()) != null) {
				list.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if( br != null ) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if(process.isAlive()) {
					process.destroy();
				}
				timer.cancel();
			}
		}
		return list;
	}

	public String getIn() {
		return in;
	}
	public void setIn(String in) {
		this.in = in;
	}
	public String getClassPath() {
		return classPath;
	}
	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public boolean isInput() {
		return isInput;
	}

	public void setInput(boolean isInput) {
		this.isInput = isInput;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	
	public interface RunnCaller{
		void onResult(List<String> result);
	}
}
最近下载更多
superman1420152584  LV1 2022年6月2日
crosa_Don  LV18 2022年4月1日
945506100  LV2 2021年9月9日
JevahChao  LV1 2021年6月22日
H.13-1.15  LV1 2021年5月18日
814035682  LV1 2021年1月29日
1736105pxr  LV1 2021年1月25日
qiushicun  LV1 2020年12月9日
luocheng  LV18 2020年11月8日
a1140038335  LV1 2020年10月6日
最近浏览更多
3334004690  LV10 2024年6月24日
求学的熊猫  LV11 2024年5月12日
denglu123321  LV4 2023年12月27日
2890892945  LV2 2023年12月26日
qq1357574774  LV2 2023年7月20日
dmyafda  LV5 2023年3月26日
柴0000 2023年3月19日
暂无贡献等级
ApolloLee 2023年2月23日
暂无贡献等级
大无语  LV1 2023年1月4日
王俊杰1 2022年9月22日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友