How to execute cmd commands via Java

前端 未结 11 2164
爱一瞬间的悲伤
爱一瞬间的悲伤 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:52

    Here is a simpler example that does not require multiple threads:

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    public class SimplePty
    {
        public SimplePty(Process process) throws IOException
        {
            while (process.isAlive())
            {
                sync(process.getErrorStream(), System.err);
                sync(process.getInputStream(), System.out);
                sync(System.in, process.getOutputStream());
            }
        }
        
        private void sync(InputStream in, OutputStream out) throws IOException
        {
            while (in.available() > 0)
            {
                out.write(in.read());
                out.flush();
            }
        }
        
        public static void main( String[] args ) throws IOException
        {
            String os = System.getProperty("os.name").toLowerCase();
            String shell = os.contains("win") ? "cmd" : "bash";
            Process process = new ProcessBuilder(shell).start();
            new SimplePty(process);
        }
    }
    

提交回复
热议问题