Writing to Windows CMD from Java

允我心安 提交于 2019-12-10 11:56:25

问题


I'm trying to be able to input commands into the command prompt on Windows from Java. I use processBuilder, open the command prompt, and get the output stream, but when I try to write to that, nothing seems to happen. Do I need to include something else, or am I going about this all wrong?

I know that I can pass arguments including commands into the command prompt when I initially start it, but my goal is to be able to open the window first, then interact with it second, not at the same time.

My code:

    ArrayList<String> commands = new ArrayList<>();
    commands.add("cmd.exe");
    commands.add("/c");
    commands.add("start");

    ProcessBuilder pb = new ProcessBuilder(commands);

    Process p = pb.start();

    BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

    stdin.write("dir");
    stdin.newLine();
    stdin.flush();

I've tried searching, but I haven't found any satisfactory answers. This code is what I've managed to piece together from that search. My end goal is to be able to write a user interface for youtube-dl, a command line program, so I can get more experienced with such things. I'd like the user to be able to pick from several options, then execute the program based on their selection.


回答1:


I was trying to do manually the youtube-dl thing, since youtube dl thing is an automatic script that uses a lot of CMD Commands.

Back to the topic, use:

Runtime.getRuntime().exec()


来源:https://stackoverflow.com/questions/41010603/writing-to-windows-cmd-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!