weixin_46063360
weixin_46063360
2021-03-04 10:53

如何用java程序执行java程序

想要用java编写一个自动测评机,要测评的程序也是java写的

目前进度:用

Process p = Runtime.getRuntime().exec("cmd /k java test/Test");

可以调用命令行来执行Test.class的main函数

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String readLine = br.readLine();
while (readLine != null) {
    readLine = br.readLine();
    System.out.println(readLine);
}

可以获得main函数的输出

那么如何向main函数中传递参数呢?

目前尝试了用

PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(p.getOutputStream())));
pw.println("Hello world!");

向main传递一个字符串“Hello world!”,但是并不会得到相应的结果

Runtime.getRuntime().exec("cmd /k hahahaha\n");

尝试直接从命令行输入,也无效

Test类:

public class Test {

    public static void main(String[] argv){
        Scanner scanner = new Scanner(System.in);

        System.out.println("Waiting for input....");
        String a = scanner.nextLine();
        System.out.println("Success!");
        System.out.println(a);
    }
}

测评机程序:

Runtime.getRuntime().exec("cmd /k start d:");
            Runtime.getRuntime().exec("cmd /k cd Chaos/Program/Java/OO/Pre2/out/production/Pre2");
            Process p = Runtime.getRuntime().exec("cmd /k java test/Test");
//            Runtime.getRuntime().exec("cmd /k hahahaha\n");
            PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(p.getOutputStream())));
            pw.println("Hello world!");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String readLine = br.readLine();
            while (readLine != null) {
                readLine = br.readLine();
                System.out.println(readLine);
            }

测评机执行结果:

Waiting for input....

 

 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答