简体   繁体   English

将值从一个 java 程序传递到另一个

[英]Passing values from one java program to another

I wrote a Java program that can execute another Java program during runtime.我写了一个 Java 程序,它可以在运行时执行另一个 Java 程序。 The program is as follows:程序如下:

import java.io.*;

public class exec {
    public static void main(String argv[]) {
        int i = 5, j = 6, k = 7;
        BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));    
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            System.out.println("Enter class name");
            String s = br.readLine();
    
            Process pro = Runtime.getRuntime().exec(s);
    
            BufferedReader in = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            String line=null;
            while((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
        } catch(Exception err) {
            err.printStackTrace();
        }
    }
}

If I execute this program it will prompt the user to enter any class name (Java program) to execute.如果我执行这个程序,它会提示用户输入任何要执行的类名(Java 程序)。 This is being done using this piece of code Process pro=Runtime.getRuntime().exec(s);这是使用这段代码完成的Process pro=Runtime.getRuntime().exec(s); . .

Once the user enters the Java class name, I should be able to pass the values 5,6,7 to the Java class entered by the user.一旦用户输入 Java 类名,我应该能够将值 5、6、7 传递给用户输入的 Java 类。 Only one value at a time should be passed and the square of that number should be calculated.一次只能传递一个值,并计算该数字的平方。

How can I do this?我怎样才能做到这一点?

You can pass the int argument to your second Java program as follows:您可以将 int 参数传递给您的第二个 Java 程序,如下所示:

String[] cmd = { s, Integer.toString(n) };
Process pro=Runtime.getRuntime().exec(cmd);

... or as a single String : ...或作为单个String

Process pro=Runtime.getRuntime().exec(String.format("%s %d", s, n);

In the second program you can implement a Server Socket then in your first program you can write a Client Socket which sends messages to second application.在第二个程序中,您可以实现一个服务器套接字,然后在您的第一个程序中,您可以编写一个将消息发送到第二个应用程序的客户端套接字。

You can see the following documentation: http://download.oracle.com/javase/tutorial/networking/sockets/您可以查看以下文档: http : //download.oracle.com/javase/tutorial/networking/sockets/

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

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