简体   繁体   English

Java Applet下载文件

[英]Java Applet Download File

I am trying to build a java applet which downloads a file to the client machine. 我正在尝试构建一个将app文件下载到客户端计算机的java applet。 As a java application this code worked fine but when I tried as an applet it does nothing. 作为一个java应用程序,这段代码运行正常,但当我尝试作为applet时,它什么也没做。 I have signed the .jar file and am not getting any security error messages 我已经签署了.jar文件,但没有收到任何安全错误消息

The Code is: 守则是:

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

Can anyone help? 有人可以帮忙吗?

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

Change that to: 改为:

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

Ideally you would put the output in either of: 理想情况下,您可以将输出放在以下任何一个中:

  1. A sub-directory (perhaps based on the package name of the main class - to avoid collisions) of user.home . user.home 的子目录 (可能基于主类的包名 - 以避免冲突)。 user.home is a place where the user is supposed to be able to read & create files. user.home是用户应该能够读取和创建文件的地方。
  2. A path as specified by the end user with the help of a JFileChooser . 最终用户在JFileChooser的帮助下指定的路径。

See this question, 看到这个问题,

Self Signed Applet Can it access Local File Systems 自签名小程序可以访问本地文件系统

I believe it will help you, you need to write your code to use PrivilegedAction. 我相信它会对您有所帮助,您需要编写代码才能使用PrivilegedAction。

http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM