如何从java小程序启动外部进程(如ping)并捕获输出?
在标准java程序中,我可以执行以下操作:如何从java小程序启动外部进程(如ping)并捕获输出?,java,process,applet,external-process,Java,Process,Applet,External Process,在标准java程序中,我可以执行以下操作: import java.io.*; public class PingApp { public static void main(String args[]) { System.out.println("about to try to launch ping..."); try { Process p = Runtime.getRuntime().exec("pin
import java.io.*;
public class PingApp
{
public static void main(String args[])
{
System.out.println("about to try to launch ping...");
try
{
Process p = Runtime.getRuntime().exec("ping -o google.com");
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}
catch(IOException e1) {
System.err.println(e1.getMessage());
}
catch(InterruptedException e2) {
System.err.println(e2.getMessage());
}
System.out.println("finished.");
}
}
我希望在java小程序中执行完全相同的操作,除了不将捕获的输出打印到终端,而是将其显示在浏览器的小程序窗口中
就这样
尝试将此代码放入小程序时遇到的错误是:
Exception in thread "AWT-EventQueue-3" java.security.AccessControlException: access denied ("java.io.FilePermission" "<<ALL FILES>>" "execute")
线程“AWT-EventQueue-3”java.security.AccessControlException中的异常:访问被拒绝(“java.io.FilePermission”“execute”)
我有没有办法避开这个AccessControlException
谢谢。您的小程序应该先签名。看看这个:
然后使用Runtime.exec启动它。这是Java的一项安全功能,可以阻止您恶意使用用户的终端或等效终端,以及读取或写入驱动器
解决此问题的唯一方法是对小程序进行签名 对,;询问用户是否允许您在其计算机上执行此操作。然而,答案很可能是“否”。在尝试其他操作之前,您是否尝试ping作为连接测试?如果是这样,为什么不尝试该操作并捕获/处理发生的任何异常呢。此外,在许多情况下,ping将成功,而后续操作将失败(防火墙或服务器不允许后续操作,ping和后续操作之间的网络或服务器的某些更改等),因此无论ping结果如何,您都需要捕获/处理异常。