使用inputStream和OutputStream读取数据并将其写入进程 [英] Using inputStream and OutputStream to read and write data to a process

查看:111
本文介绍了使用inputStream和OutputStream读取数据并将其写入进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在运行 .class 文件作为进程。 .class 文件是一个简单的程序,要求用户输入数字,接受输入并将用户的输入打印回屏幕。
到目前为止,我已经设法通过 InputStream 从控制台上的进程中打印了输入数字:语句,并写入了用户输入的输入通过 OutputStream 。我无法在屏幕上打印最后的语句,应该是

I am currently running a .class file as a process. The .class file is a simple program that asks the user to input a number, takes the input and prints the user's input back to the screen. Up to now, i have managed to print the "Enter a number: " statement from the process on the console through InputStream and write the input entered by the user through OutputStream. I am unable to print the last statements on the screen, which should be


您输入的是: + userinput

"You entered : " + userinput

我的代码是:

String command [] = {"java" , "-cp", "C:\\Users\\Mahika\\Documents\\NetBeansProjects\\JavaTest\\compilerTest", "InputInteger"};
ProcessBuilder pb = new ProcessBuilder(command);
Process p = pb.start();
System.out.println("Process started");
BufferedReader br = new BufferedReader (new InputStreamReader(p.getInputStream()));
String output = null;

while((output = br.readLine()) != null){
    System.out.println(output);
    break;
}
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

OutputStream os = p.getOutputStream();
PrintStream ps = new PrintStream(os);
os.write(i);
os.flush();  

我不知道如何使用 InputStream 再次阅读您输入的内容: +用户输入。

I don't know how to use InputStream again to read the "You entered:" + userinput.

推荐答案

这应该有效:

public static void main(String[] args) throws IOException {
    String command[] = {"java.exe", "-cp", "C:\\Users\\Mahika\\Documents\\NetBeansProjects\\JavaTest\\compilerTest", "InputInteger"};
    ProcessBuilder pb = new ProcessBuilder(command);
    Process p = pb.start();
    System.out.println("Process started");
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    System.out.println(br.readLine());
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    PrintStream ps = new PrintStream(p.getOutputStream(), true);
    ps.println(i);
    System.out.println(br.readLine());
}

只需确保在 InputInteger中输入提示类由换行符完成(例如,由 println 创建,而不是由 print 创建)。

Just make sure that input prompt in InputInteger class is finished by a newline character (e.g. created by println and not print).

这篇关于使用inputStream和OutputStream读取数据并将其写入进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆