各位前辈:
系统是ubuntu 12.04,jdk-1.7.0_21。
Applet的功能是执行本地的一个hello程序,获取hello程序的输出字符串,然后将字符串用g.drawString()画到窗口上。
在eclipse里可以正常运行,将AppletHello.class嵌到html后,用appletviewer也可以运行.html文件。但是用浏览器打开.html文件,applet会运行,但是不能在窗口打印出"hello"字符串——就是
Runtime.getRuntime().exec(command);
这句话的输出结果。
将AppletHello.class打包签名,修改java.policy,这些方法都试了。都没效果。
代码:
AppletHello.java程序
1 import java.applet.Applet; 2 import java.awt.Graphics; 3 import java.io.*; 4 5 public class AppletHello extends Applet { 6 private static final long serialVersionUID = 1L; 7 String cmd; 8 String key; 9 10 public void init() { 11 System.out.println("init"); 12 cmd = "sudo ./hello"; 13 key = null; 14 } 15 16 public void start() { 17 System.out.println("start"); 18 execCommand(cmd); 19 } 20 21 public void stop() { 22 System.out.println("stop"); 23 } 24 25 public void destroy() { 26 System.out.println("destroy"); 27 } 28 29 public int execCommand(String command) { 30 int execRes = -1; 31 try { 32 Process p = null; 33 InputStream is = null; 34 InputStreamReader isr = null; 35 BufferedReader br = null; 36 37 p = Runtime.getRuntime().exec(command); 38 is = p.getInputStream(); 39 isr = new InputStreamReader(is); 40 br = new BufferedReader(isr); 41 String str = null; 42 if ((str = br.readLine()) != null) { 43 key = str; 44 System.out.println(str); 45 System.out.flush(); 46 } 47 48 try { 49 int intWaitFor = p.waitFor(); 50 System.out.println("intWaitFor:" + intWaitFor); 51 } catch (InterruptedException e) { 52 System.out.println("Error waitfor.\n"); 53 e.printStackTrace(); 54 } 55 56 int exitVal = p.exitValue(); 57 execRes = exitVal; // when execRes == 0, success; execRes == 1, fail 58 System.out.println("exitVal:" + exitVal); 59 is.close(); 60 isr.close(); 61 br.close(); 62 63 // p.destroy(); 64 65 } catch (IOException e) { 66 System.out.println("Error exec.\n"); 67 } 68 69 return execRes; 70 } 71 72 @Override 73 public void paint(Graphics g) { 74 g.drawString("key:" + key, 25, 25); 75 } 76 }
解决了,把hello程序放到主文件夹下。