读书人

When Runtime.exec() won#039;t - Runtime

发布时间: 2012-11-09 10:18:47 作者: rapoo

When Runtime.exec() won't - Runtime.exec的陷阱

???? 原文比较长,在这里就不转载了,给出地址:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

    文中总结了几个要点:
    You cannot obtain an exit status from an external process until it has exited
    直到一个外部进程退出,你才能获取其退出状态值。
    正确代码
    ??
    缺陷代码
    ??You must use Runtime.exec() to execute programs
    ?你必须使用Runtime.exec()来执行程序(这句我不太理解)You cannot use Runtime.exec() like a command line
    你不能用Runtime.exec()来执行像命令行那样的程序,如重定向输出:Process proc = rt.exec("java jecho 'Hello World' > test.txt");?
    这段程序的意图是运行一个名为jecho的Java程序,并将其输出重定向到test.txt文件中。 但这种写法得不到正确结果,因为Runtime.exec()方法并不能很好的执行这种较为复杂的命令行,必须通过自己处理程序输出并写入到相应的文件

?最后给出完整的代码:

Class StreamGobbler 用于处理输出流:

?TestExec则是测试用的main class

?

测试例子: java TestExec "iexplore www.sina.com.cn" (因为iexplore.exe已经在windows的环境变量Path中,所以这些调用没有问题,否则就要写绝对路径)?



学习了,谢谢!

读书人网 >软件架构设计

热点推荐