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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read