本文介绍了如何在命令提示符下多次运行BufferedReader来输入值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我提出了一个正确的日期,但如果我把其他东西放在哪里,那就是错误。我想知道如何在命令提示符下写入多个输入。
例如,我将05-13-2018作为的变量写入writer.write()。如果我也想在那个代码下面输入一个值然后执行那么有什么办法。如果你不明白我想要达到的目的,请给我留言。再次感谢您的帮助

Although I put a correct date, if I where to put something else and it be an error. I want to know how can I write multiple inputs to the command prompt.For example, I put "05-13-2018" as the variable for writer.write(). Is there any way underneath that code to enter a value if I wanted too and then have that execute. Please message me, if you don't understand what I am trying to achieve. Thanks again for all your help

import java.io.*;
import java.util.ArrayList;


public class command{
    public static void main(String[] args) {


        String command="cmd /c date";

        try {
            Process process = Runtime.getRuntime().exec(command);
            OutputStreamWriter outputt = new OutputStreamWriter(process.getOutputStream());


            BufferedWriter writer = new BufferedWriter(outputt);
            writer.write("05-13-2018");
            writer.close();




            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            reader.close();


        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}


推荐答案

当命令尝试读取值时,它会读取所有可用输入并将其视为一个值。您必须在正确的时间写入并刷新值,并且在这方面,避免所有缓冲:

It seems that when the command tries to read a value, it will read all available input and treat it as one value. You have to write and flush the values at the right time and in that regard, avoid all buffering:

String command="cmd /c date";
try {
    Process process = Runtime.getRuntime().exec(command);
    try(Writer writer = new OutputStreamWriter(process.getOutputStream());
        Reader reader = new InputStreamReader(process.getInputStream())) {

        CharBuffer buf = CharBuffer.allocate(80);
        int tries = 3;
        while(process.isAlive()) {
            while(reader.ready() && reader.read(buf)>0) {
                System.out.append(buf.flip());
                buf.clear();
            }
            if(tries-- == 0) {
                process.destroy();
                break;
            }
            writer.write("05-13-2018");
            writer.flush();
            while(!reader.ready()) Thread.sleep(200);
        }
    }
} catch(IOException|InterruptedException e) {
    e.printStackTrace();
}

这篇关于如何在命令提示符下多次运行BufferedReader来输入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 20:59