问题
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