Java Runtime.getRunTime().exec(CMD) not supporting pipes

前端 未结 1 1977
粉色の甜心
粉色の甜心 2021-01-07 05:03

I\'m attempting to write a program that will display and be able to update your IP address settings using a JFrame window. I am looking at running this purely on windows so

相关标签:
1条回答
  • 2021-01-07 05:16

    Fortunately, there is a way to run a command containing pipes. The command must be prefixed with cmd /C. e.g.:

    public static void main(String[] args) throws Exception {
        String command = "cmd /C netstat -ano | find \"3306\"";
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
        if (process.exitValue() == 0) {
            Scanner sc = new Scanner(process.getInputStream(), "IBM850");
            sc.useDelimiter("\\A");
            if (sc.hasNext()) {
                System.out.print(sc.next());
            }
            sc.close();
        } else {
            Scanner sc = new Scanner(process.getErrorStream(), "IBM850");
            sc.useDelimiter("\\A");
            if (sc.hasNext()) {
                System.err.print(sc.next());
            }
            sc.close();
        }
        process.destroy();
    }
    

    Notes

    • The console of Windows use IBM850 encoding. See Default character encoding for java console output.
    • See Stupid Scanner tricks... for useDelimiter("\\A").
    0 讨论(0)
提交回复
热议问题