how does one call a windows (dos-like) command from within java?

such as net stop spooler

can one capture the resulting text (such as, spooler stopping, or error such and such)

Dani AI

Generated

As noted, Java can start OS commands. For a practical, robust solution prefer ProcessBuilder (it handles argument lists, environment and redirection). For your example , you can run net stop spooler directly or via cmd /c if you need shell features (redirection, pipes, or built‑ins).

Example pattern (read the process output to capture the text and avoid blocking):

ProcessBuilder pb = new ProcessBuilder("net", "stop", "spooler");
pb.redirectErrorStream(true); // merge stderr into stdout
Process p = pb.start();

StringBuilder output = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
    String line;
    while ((line = br.readLine()) != null) {
        output.append(line).append(System.lineSeparator());
    }
}
int exitCode = p.waitFor();
// output.toString() now contains the combined output; check exitCode for success

Notes and cautions: read the process streams (or use redirectErrorStream(true)) to prevent deadlocks; parse the captured text rather than relying only on exit codes. net stop spooler generally requires administrative rights — run the JVM elevated or the command will fail. Be mindful of platform encoding (command output may use a system code page), and do not build command lines from untrusted input to avoid injection.

For the API details and edge cases, see the Java ProcessBuilder documentation: ProcessBuilder (Java SE 8).

Recommended Answers

All 2 Replies

See the Process and Runtime classes for that.

ok

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.