简体   繁体   English

从cmd重定向输出时,为什么输出文件为空?

[英]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. 我正在创建一个JAVA Web应用程序以在线判断代码。 I am taking the .java file uploaded by user and storing it in C:\\uploads. 我正在获取用户上传的.java文件,并将其存储在C:\\ uploads中。 Then using the ProcessBuilder class, I am compiling and executing the java file on the server. 然后使用ProcessBuilder类,在服务器上编译并执行Java文件。 While executing, I am redirecting the output of the JAVA program to output.txt. 执行期间,我将JAVA程序的输出重定向到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. 但是发生的问题是在执行时,尽管创建了output.txt文件,但该文件为空。

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. PS-当我仅创建用于执行相同操作的JAVA程序时,不会发生此问题。

If you're using jdk 1.7 then you can try something like this: 如果您使用的是jdk 1.7,则可以尝试如下操作:

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? 我不是控制台/ bash的高级用户,但是您不错过几个空格吗? The line should be like this: 该行应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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