ProcessBuilder in Java to create a basic online Judge
Last Updated :
18 Jan, 2023
We have discussed Process and Runtime to create an external process. In this post, ProcessBuilder is discussed which serves the same purpose.
Let us understand an application where we need to get source code and find out the language. The application needs a string (containing source code) as input. The application needs to find out the language in which source code in written. Source codes will be having a relevant extension. For example –
- Code in C language will have ".c" extension
- Code in C++ will have ".cpp" extension
- Code in Java will have ".java" extension
- Code in Python will have ".py" extension
Using the name of input file the required language, to be used, can be found out.
Recall that compiling a code in java is done with command –
"javac Main.java"
and to execute it we use -
"java Main"
Similar commands are there for other languages. Therefore we need a separate text file containing all the commands which our software should execute one by one.
In case of error (Runtime or Compiler Errors) our application should write the error logs in a separate text file. Whatever output the source code is producing, our application should write it in another text file.
We use "ProcessBuilder" class in "Language" package which can execute OS processes.
Now we must create a process first-
ProcessBuilder pb = new ProcessBuilder("cmd");
Note that we are using "cmd" so that our commands can easily be executed in command prompt.
Suppose that we’re having our commands in "commands.txt" file and we wish to store output in "output.txt" along with error logs in "error.txt". We should tell the ProcessBuilder object about them all. The "ProccessBuilder" class has methods –
- public ProcessBuilder redirectInput(File file)
- public ProcessBuilder redirectOutput(File file)
- public ProcessBuilder redirectError(File file)
All grounds have been set, we just need to start our process. Invoking a process is just like a thread. We use- pb.start()
to start our process.
Below is a sample java code to compile and run another java code-
Java
// Java program to demonstrate use of ProcessBuilder
// to compile and run external files.
import java.util.*;
import java.io.*;
class Main
{
public static void main(String [] args) throws IOException
{
try {
// create a process
ProcessBuilder pb = new ProcessBuilder("cmd");
// take all commands as input in a text file
File commands = new File("E:\\test\\commands.txt");
// File where error logs should be written
File error = new File("E:\\test\\error.txt");
// File where output should be written
File output = new File("E:\\test\\output.txt");
// redirect all the files
pb.redirectInput(commands);
pb.redirectOutput(output);
pb.redirectError(error);
// start the process
pb.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
For the code to work correctly do the following steps-
- Create a folder named Text in E directory.
- Create two empty text files named "error.txt" and "output.txt".
- Create a text file named "commands.txt" which should have –
javac Demo.java
java Demo - Create a file named "Demo.java" where the source code should be present and "main(String[] args)" function should be present in "Demo" class.
- Finally compile and execute the code written above.
- If there are any errors the logs would be present in “error.txt” file, last the output will be shown in "output.txt".
Warnings:
- Make sure that the code, you wish to compile and execute, doesn’t contain an infinite loop or something like that which may cause your program to run forever. You can take care of this case by allowing the source code to run for a fixed time. For Example – if code takes more than 10 seconds to run, throw an error saying something like “Time Limit Exceeded”. For this you may use “waitFor()” function in “Process” class.
- You must check that the code compiles correctly, only then you should try to run it, otherwise display the error log files.
Advantages-
- You can create your own online judge using this technique.
- It will help you to link your software with the OS directly.
Differences between Runtime.getRuntime.exec() and ProcessBuilder :
Runtime.getRuntime.exec() executes the specified string command in a separate process. The ProcessBuilder, on the other hand, only takes a List of strings, where each string in the array or list is assumed to be an individual argument. The arguments are then joined up into a string, then passed to the OS to execute.
// ProcessBuilder takes a list of arguments
ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
// Runtime.getRuntime.exec() takes a single string
Runtime.getRuntime.exec("myCommand myArg1 myArg2")
Similar Reads
Generate Junit Test Cases Using Randoop API in Java Here we will be discussing how to generate Junit test cases using Randoop along with sample illustration and snapshots of the current instances. So basically in Development If we talk about test cases, then every developer has to write test cases manually. Which is counted in the development effort
4 min read
JUnit - Testcases for Credit Card Validation as a Maven Project In this article let us see a much-required functionality that is credit card validation as well as its relevant JUnit test cases for given credit card numbers. In an e-commerce project, credit card payment is the valid and much desired required functionality. We need to have a proper validation mech
6 min read
Calling an External Program in Java using Process and Runtime Java contains the functionality of initiating an external process - an executable file or an existing application on the system, such as Google Chrome or the Media Player- by simple Java code. One way is to use following two classes for the purpose: Process class Runtime class The Process class pres
2 min read
Java Servlet and JDBC Example | Insert data in MySQL Prerequisites: Servlet, JDBC Connectivity To start with interfacing Java Servlet Program with JDBC Connection: Proper JDBC Environment should set-up along with database creation. To do so, download the mysql-connector.jar file from the internet, As it is downloaded, move the jar file to the apache-t
4 min read
How to Open Chrome Browser Using Selenium in Java? Selenium is an open-source popular web-based automation tool. The major advantage of using selenium is, it supports all browsers like Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari, works on all major OS, and its scripts are written in various languages i.e Java, Python, JavaScript, C#,
3 min read
Java Application with JOptionPane: Calculator, Numbers, Discounts, and Student Assessment In this article, we will create a simple application that is created using the Java programming language with the help of the JOptionPane class. This application has various features that can assist users in various situations. Available Features:1. Arithmetic Operations (Calculator): This applicati
5 min read