Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 304|回复: 0

[Java基础知识]如何用java启动windows命令行程序

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-1 08:56:12 | 显示全部楼层 |阅读模式
    这是摘自《More java pitfalls 中文版》上的例子。

    先请编译和运行下面程序:

    import java.util.*;
    import java.io.*;

    public class BadExecJavac2
    {
         public static void main(String args[])
         {
             try
             {            
                 Runtime rt = Runtime.getRuntime();
                 Process proc = rt.exec("javac");
                 int exitVal = proc.waitFor();
                 System.out.println("Process exitValue: " + exitVal);
             } catch (Throwable t){
                 t.printStackTrace();
             }
         }
    }  
      
       
       
         
       
                         
         
       
      

        我们知道javac命令,当不带参数运行javac 程序时,它将输出帮助说明,为什么上面程序不产生任何输出并挂起,永不完成呢?java文档上说,由于有些本地平台为标准输入和输出流所提供的缓冲区大小有限,如果不能及时写入子进程的输入流或者读取子进程的输出流,可能导致子进程阻塞,甚至陷入死锁。所以,上面的程序应改写为:

    import java.util.*;
    import java.io.*;

    public class MediocreExecJavac
    {
         public static void main(String args[])
         {
             try
             {            
                 Runtime rt = Runtime.getRuntime();
                 Process proc = rt.exec("javac");
                 InputStream stderr = proc.getErrorStream();
                 InputStreamReader isr = new InputStreamReader(stderr);
                 BufferedReader br = new BufferedReader(isr);
                 String line = null;
                 System.out.println("<ERROR>");
                 while ( (line = br.readLine()) != null)
                     System.out.println(line);
                 System.out.println("</ERROR>");
                 int exitVal = proc.waitFor();
                 System.out.println("Process exitValue: " + exitVal);
             } catch (Throwable t){
                 t.printStackTrace();
             }
         }
    }

    下面是正确的输出:

    D:java>java   MediocreExecJavac
    <ERROR>
    Usage: javac <options> <source files>
    where possible options include:
       -g                         Generate all debugging info
       -g:none                    Generate no debugging info
       -g:{lines,vars,source}     Generate only some debugging info
       -nowarn                    Generate no warnings
       -verbose                   Output messages about what the compiler is doing
       -deprecation               Output source locations where deprecated APIs are used
       -classpath <path>          Specify where to find user class files
       -cp <path>                 Specify where to find user class files
       -sourcepath <path>         Specify where to find input source files
       -bootclasspath <path>      Override location of bootstrap class files
       -extdirs <dirs>            Override location of installed extensions
       -endorseddirs <dirs>       Override location of endorsed standards path
       -d <directory>             Specify where to place generated class files
       -encoding <encoding>       Specify character encoding used by source files
       -source <release>          Provide source compatibility with specified release

       -target <release>          Generate class files for specific VM version
       -version                   Version information
       -help                      Print a synopsis of standard options
       -X                         Print a synopsis of nonstandard options
       -J<flag>                   Pass <flag> directly to the runtime system

    </ERROR>
    Process exitValue: 2

    D:java>

        下面是一个更一般的程序,它用两个线程同步清空标准错误流和标准输出流,并能根据你所使用的windows操作系统选择windows命令解释器command.com或cmd.exe,然后执行你提供的命令。


    import java.util.*;
    import java.io.*;

    class StreamGobbler extends Thread
    {
         InputStream is;
         String type;  //输出流的类型ERROR或OUTPUT
          
         StreamGobbler(InputStream is, String type)
         {
             this.is = is;
             this.type = type;
         }
          
         public void run()
         {
             try
             {
                 InputStreamReader isr = new InputStreamReader(is);
                 BufferedReader br = new BufferedReader(isr);
                 String line=null;
                 while ( (line = br.readLine()) != null)
                 {
                     System.out.println(type + ">" + line);
                     System.out.flush();
                 }
                 } catch (IOException ioe)
                   {
                     ioe.printStackTrace();   
                   }
         }
    }

    public class GoodWindowsExec
    {
         public static void main(String args[])
         {
             if (args.length < 1)
             {
                 System.out.println("USAGE: java GoodWindowsExec <cmd>");
                 System.exit(1);
             }
             
             try
             {            
                 String osName = System.getProperty("os.name" );
                 System.out.println("osName: " + osName);
                 String[] cmd = new String[3];

                 if(osName.equals("Windows XP") ||osName.equals("Windows 2000"))
                 {
                     cmd[0] = "cmd.exe" ;
                     cmd[1] = "/C" ;
                     cmd[2] = args[0];
                 }
                 else if( osName.equals( "Windows 98" ) )
                 {
                     cmd[0] = "command.com" ;
                     cmd[1] = "/C" ;
                     cmd[2] = args[0];
                 }
                  
                 Runtime rt = Runtime.getRuntime();
                 System.out.println("Execing " + cmd[0] + " " + cmd[1]+ " " + cmd[2]);
                 Process proc = rt.exec(cmd);
                 // any error message?
                 StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");        
                 // any output?
                 StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
                      
                 // kick them off
                 errorGobbler.start();
                 outputGobbler.start();
                                          
                 // any error???
                 int exitVal = proc.waitFor();
                 System.out.println("ExitValue: " + exitVal);
             
             } catch (Throwable t){
                 t.printStackTrace();
             }
         }
    }
    下面是一个测试结果:

    D:java>java  GoodWindowsExec "copy Test.java Test1.java"
    osName: Windows XP
    Execing cmd.exe /C copy Test.java Test1.java
    OUTPUT>已复制         1 个文件。
    ExitValue: 0

    D:java>

    下面的测试都能通过(windows xp+jdk1.5)

    D:java>java   GoodWindowsExec dir

    D:java>java   GoodWindowsExec Test.java

    D:java>java   GoodWindowsExec regedit.exe

    D:java>java   GoodWindowsExec NOTEPAD.EXE

    D:java>java   GoodWindowsExec first.ppt

    D:java>java   GoodWindowsExec second.doc

      

      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/1/085611969.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-5-2 13:31 , Processed in 0.367514 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表