简体   繁体   中英

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;
}

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

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);

    ...

}

I´m not an advanced console/bash user but aren't you missing a couple of spaces? The line should be like this:

String commands[]={"CMD", "/C","cd C:\\uploads && java "+fileName+" > output.txt"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM