2012-10-17 59 views
2

我试图在Java程序执行cmd命令执行cmd命令,我想这个代码在Java小程序

import java.io.InputStream; 
import java.io.IOException; 
import java.applet.Applet; 
import java.awt.*; 
public class execute extends Applet{ 
String output=""; 
public void init(){ 
try { 
// Execute command 
String command = "MYCMDCOMMAND"; 
Process child = Runtime.getRuntime().exec(command); 
// Get the input stream and read from it 
InputStream in = child.getInputStream(); 
int c= in.read(); 
while ((c = in.read()) != -1) { 
output =output+((char)c); 
} 
in.close(); 
} 
catch (IOException e) { 
} 
System.out.println(output); 
} 
public void paint(Graphics g){ 
g.drawString(output,60,100); 
} 
} 

然后写了这个HTML文件,并在同一目录下保存它:

<html> 
<head><title>Applet</title> 
<body> 
<applet code="execute.class",height="200" width="200"> 
</body> 
</html> 

我在这里要做的是在applet中运行ls shell命令并显示结果。

该代码编译没有错误。但是当我在浏览器中打开html文件时,我只是得到一个灰色方块。

这是因为安全问题,我什么都没有得到?还是因为代码中的错误?

+0

我不知道,如果你试图做的是合法的小程序,尤其是未签名的,给定了他们的沙箱限制另外,你的代码似乎并不尊重Swing的线程规则。另外,你的错误捕捉的缺乏是相当危险的。 –

+2

简短的答案是** DON'T **。小应用程序的重点在于您对最终用户系统拥有非常有限的一系列权限,执行外部命令是最为严重的安全问题。使用专用应用程序以及类似[Java Web Start](http://docs.oracle.com/javase/tutorial/deployment/webstart/)来部署它。您仍然会遇到安全问题,但这些解决方案为客户提供了一个更清晰的解决方案 – MadProgrammer

+0

1)*“这是因为安全问题,我什么都没得到?”*答案将在[Java控制台](http://www.java.com/en/download/help/javaconsole.xml)。 2)作为一般技巧,将catch(IOException e){catch(IOException e){e.printStackTrace(); }'3)HTML格式错误,请使用[验证服务](http://validator.w3.org/)进行检查。 –

回答

0

你必须小心一些事情。

  1. 你必须复制&粘贴HTML文件.bin文件编译你以后
  2. 你的HTML文件名是Applet和你的类名execute.class所以这意味着你不必包如果u有你必须保存HTML文件,如“PACKAGENAME/execute.class”
  3. 在控制面板/ Java中你必须禁用安全