Springboot实现在线Java代码运行

  @PostMapping("/run")
  public String Run(@RequestBody Map<String,String> map) throws IOException, InterruptedException {
    // 创建临时文件
    File tempFile = new File(System.getProperty("java.io.tmpdir"), "test.py");
    // 将前端传入的代码写入临时文件
    writeToFile(map.get("code"), tempFile);
    try {
      ProcessBuilder processBuilder = new ProcessBuilder("D:\\Java\\python3.6\\python.exe",tempFile.getAbsolutePath());
      // 将错误流与输出流合并
      processBuilder.redirectErrorStream(true);
      // 开启进程
      Process process = processBuilder.start();
      // 使用字符流返回命令行执行结果
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
      // 使用可变String类 拼接响应对象并返回
      StringBuilder result = new StringBuilder();
      // 声明接收变量
      String line;
      // 获取文件流中数据
      while ((line = reader.readLine()) != null) {
        // 拼接响应对象
        result.append(line).append("\n");
      }
      // 获取程序的执行结果 这个方法会阻塞主线程等待命令行执行完毕后返回
      int exitCode = process.waitFor();
      // 运行成功
      if (exitCode == 0) {
        return result.toString();
      } else {
        return "Command execution failed with exit code: " + exitCode;
      }
    } catch (IOException | InterruptedException e) {
      return "Error executing command: " + e.getMessage();
    }
  }




  @PostMapping("/execute")
  public String executeCode(@RequestBody Map<String, String> map) {
    try {
      // 创建临时文件
      File tempFile = new File(System.getProperty("java.io.tmpdir"), "test.java");
      // 将前端传入的代码写入临时文件
      writeToFile(map.get("code"), tempFile);
      // 编译代码
      compileCode(tempFile);
      // 执行代码
      return executeCompiledCode();
    } catch (Exception e) {
      return "Error executing code: " + e.getMessage();
    }
  }

  private void writeToFile(String code, File file) throws IOException {
    // 创建字符缓冲流 写入字符型数据
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
      // 写入数据
      writer.write(code);
    }
  }

  private void compileCode(File file) throws IOException {
    // 获取编译器
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // 获取文件管理器
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    // 创建编译任务
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    // 执行编译
    task.call();
    fileManager.close();
  }

  private String executeCompiledCode() throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, java.lang.reflect.InvocationTargetException {
    // 获取类加载器
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{new File(System.getProperty("java.io.tmpdir")).toURI().toURL()});
    // 加载类
    Class<?> compiledClass = classLoader.loadClass("test");
    // 执行 main 方法
    Method mainMethod = compiledClass.getMethod("main", String[].class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(outputStream);
    PrintStream originalOut = System.out;
    System.setOut(printStream);
    try {
      // 执行方法
      mainMethod.invoke(null, new Object[]{new String[0]});
      // 刷新系统输出流
      System.out.flush();
      // 返回响应对象流
      return outputStream.toString();
    } finally {
      System.setOut(originalOut);
    }
  }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值