How to execute cmd commands via Java

前端 未结 11 1977
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 13:59

I am trying to execute command line arguments via Java. For example:

// Execute command
String command = \"cmd /c start cmd.exe\";
Process child = Runtime.ge         


        
11条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:45

    Every execution of exec spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it's effectively a no-op).

    If you want to compose requests, you'll need to do this within a single call to exec. Bash allows multiple commands to be specified on a single line if they're separated by semicolons; Windows CMD may allow the same, and if not there's always batch scripts.

    As Piotr says, if this example is actually what you're trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:

    String[] filenames = new java.io.File("C:/").list();
    

提交回复
热议问题