How do I execute Windows commands in Java?

前端 未结 5 1652
遇见更好的自我
遇见更好的自我 2020-11-29 10:09

I\'m working on a project, and it will give you a list of Windows commands. When you select one, it will perform that command. However, I don\'t know how to do that. I was g

5条回答
  •  既然无缘
    2020-11-29 10:23

    Old question but might help someone passing by. This is a simple and working solution. Some of the above solutions don't work.

    import java.io.IOException;
    import java.io.InputStream;
    
    public class ExecuteDOSCommand
    {
        public static void main(String[] args)
        {
            final String dosCommand = "cmd /c dir /s";
            final String location = "C:\\WINDOWS\\system32";
            try
            {
                final Process process = Runtime.getRuntime().exec(dosCommand + " " + location);
                final InputStream in = process.getInputStream();
                int ch;
                while((ch = in.read()) != -1)
                {
                    System.out.print((char)ch);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    

    Source: http://www.devx.com/tips/Tip/42644

提交回复
热议问题