Java Applet下载文件

3

我正在尝试构建一个Java小程序,将文件下载到客户机。作为Java应用程序,这段代码运行良好,但当我尝试作为小程序运行时,它什么也不做。我已经对.jar文件进行了签名,并且没有收到任何安全错误消息。

代码如下:

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){     
}  
}
}

有人可以帮忙吗?


  1. printFile 请使用常见的类/方法/属性命名规范。
  2. java.io.BufferedInputStreamtry 中不需要使用完全限定名称。请改用例如 BufferedInputStream
  3. 不要忽略 IOException,调用 ioe.printStacktrace()
  4. 我了解 Google 不鼓励直接编程访问。请尝试其他网站。
  5. 请一致缩进代码块。
- Andrew Thompson
2个回答

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.home是用户应该能够读取和创建文件的地方。
  2. 由最终用户通过JFileChooser指定的路径。

你也可以将文件保存到 java.io.tmpdir,这是用户的临时目录。 - nates

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接