Search code examples
javaweb-applicationsprocessbuilder

Why am I getting the output file as empty when I am redirecting the output from cmd?


I am creating a JAVA Web Application for judging the code online. I am taking the .java file uploaded by user and storing it in C:\uploads. Then using the ProcessBuilder class, I am compiling and executing the java file on the server. While executing, I am redirecting the output of the JAVA program to output.txt. The program gets compiled alright. But the problem occurring is while executing, though the output.txt file gets created, the file is empty.

Here is the code for execution

public static boolean executeCode(int timeLimit,String fileName)
{
    fileName=fileName.substring(0,fileName.length()-5);  //to remove .java
    String commands[]={"CMD", "/C","cd C:\\uploads && java"+fileName+">output.txt"};
    ProcessBuilder p=new ProcessBuilder(commands);
    p.redirectErrorStream(true);
    Process process=null;
    boolean errCode=false;
    try {
        long start=System.nanoTime();
        process=p.start();
         errCode=process.waitFor(timeLimit,TimeUnit.MILLISECONDS); 
         long end=System.nanoTime();
         System.out.println("Duration="+(end-start));
        } catch (IOException e) {
        e.printStackTrace();
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    return errCode;
}

P.S. - This problem didn't occur when I created just a JAVA program for doing the same thing.


Solution

  • If you're using jdk 1.7 then you can try something like this:

    public static boolean executeCode(int timeLimit,String fileName)
    {
        String commands[]={"CMD", "/C","cd C:\\uploads && javac " + fileName};
        ProcessBuilder p=new ProcessBuilder(commands);
        p.redirectErrorStream(true);
    
        File output = new File("C:\\uploads\\output.txt");
        p.redirectOutput(output);
    
        ...
    
    }