Java calls Windows command line using runtime

Source: Internet
Author: User

When Java needs to invoke the Windows system for interaction, it can be manipulated using runtime.

Example:

1, call the window to get information about Java-related

        Runtime RT = Runtime.getruntime ();         = Rt.exec ("WMIC process where caption=\" javaw.exe\ "Get Caption,commandline/value");         New BufferedReader (new  InputStreamReader (P.getinputstream ()));         NULL ;          while ((Line=br.readline ()) =null) {            System.out.println (new String (line.getbytes (), "GBK"));        }        Br.close ();        System.out.println ("over");

The results appear as follows:

2. Querying windows in Java port: 80

        Runtime RT = Runtime.getruntime ();         // OK New BufferedReader (new  InputStreamReader (P.getinputstream ()));                           NULL ;          while ((Line=br.readline ()) =null) {            System.out.println (new String (line.getbytes (), "GBK"));        }        Br.close ();        System.out.println ("over");

The result is:

3. Execute BAT file

Runtime RT = Runtime.getruntime (); Rt.exec ("cmd/k start D:/run/hello.bat");

Note: The simple bat that is written can be executed as described above, but: not when hello needs to rely on external environment variables

For example, I need to launch Tomcat to publish a web

Rt.exec ("cmd/k start D:/run/tomcat/bin/startup.bat"); // will error
// Use && to Stitch rt.exec ("cmd/k D: && cd d:/run/tomcat/bin && startup.bat") when using exec to execute multiple commands ; // OK
cmd dir is to close the command window after executing the dir command.  cmddir  is a command window that is not closed after the dir command is executed.  cmdstartdir  will open a new window and execute the dir instruction, the original window will be closed.  cmdstartdir will open a new window and execute the dir instruction, the original window will not be closed.

Java calls Windows command line using runtime

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.