简体   繁体   中英

How make runtime.exec() working on multi-OS in Java?

I call a runtime execution on OSX adding "/bin/bash", "-c" before the command, such as:

Runtime runtime = Runtime.getRuntime();  
Process process = runtime.exec(new String[] { "/bin/bash", "-c", cmd });  

I know that it is different for Windows and Linux. How can I make sure that my runtime command works on multi-OS?

Thank you.

Use something like:

    String osName = System.getProperty("os.name");
    if(osName.startsWith("Windows")) {
        // windows code
    } else {
        if(osName.startsWith("Linux") {
             // linux code
        } else {
             // mac code
        }
    }

Disclaimer: This is just orientative. There are still many corner cases (eg FreeBSD) that you need to test to get correct behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM