-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExecutionManager.java
30 lines (27 loc) · 1.1 KB
/
ExecutionManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.io.*;
public class ExecutionManager {
public static String compileAndRun(String code) {
try {
// Save the code to a temporary Java file
File tempFile = new File("Temp.java");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
writer.write(code);
}
// Compile the Java file
Process compileProcess = Runtime.getRuntime().exec("javac Temp.java");
compileProcess.waitFor();
// Run the compiled Java file
Process runProcess = Runtime.getRuntime().exec("java Temp");
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
return output.toString();
} catch (Exception e) {
e.printStackTrace();
return "Error during compilation or execution";
}
}
}