2011-11-23 110 views
3

我正在尝试构建一个java applet,它将文件下载到客户机。作为一个Java应用程序,这段代码工作正常,但是当我作为一个applet尝试时,它什么都不做。我已经签署了.jar文件和我没有得到任何安全错误消息Java Applet下载文件

的代码是:

import java.io.*; 
import java.net.*; 
import javax.swing.*; 


public class printFile extends JApplet { 

public void init(){ 

try{ 
    java.io.BufferedInputStream in = new java.io.BufferedInputStream(new 
    java.net.URL("http://www.google.com").openStream()); 
    java.io.FileOutputStream fos = new java.io.FileOutputStream("google.html"); 
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024); 
    byte data[] = new byte[1024]; 
    while(in.read(data,0,1024)>=0) 
    { 
     bout.write(data); 
    } 
    bout.close(); 
    in.close(); 


} catch(IOException ioe){  
} 
} 
} 

谁能帮助?

+0

1)'printFile'请使用类/方法/属性名称的通用命名法。 2)'java.io.BufferedInputStream'不需要'try'中的全限定名。使用例如改为'BufferedInputStream'。 3)不要吞下'IOException',调用'ioe.printStacktrace()'4)我了解Google不鼓励直接编程访问。尝试其他网站。 5)请一致地缩进代码块。 –

回答

4
FileOutputStream fos = new FileOutputStream("google.html"); 

修改成:

File userHome = new File(System.getProperty("user.home")); 
File pageOutput = new File(userHome, "google.html"); 
FileOutputStream fos = new FileOutputStream(pageOutput); //see alternative below 

理想情况下,你会把输出中的任何一种:

  1. 一个子目录(也许是基于对主要类的包名 - 避免碰撞)user.homeuser.home是用户应该能够读取&创建文件的地方。
  2. 最终用户在JFileChooser的帮助下指定的路径。
+0

非常感谢,解决了我的问题 – user1061995

+0

您也可以将文件保存到用户临时目录的'java.io.tmpdir'。 – nates