Java 小程序下载文件 [英] Java Applet Download File

查看:24
本文介绍了Java 小程序下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a java applet which downloads a file to the client machine. As a java application this code worked fine but when I tried as an applet it does nothing. I have signed the .jar file and am not getting any security error messages

代码是:

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

有人可以帮忙吗?

推荐答案

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

理想情况下,您会将输出放在以下任一位置:

Ideally you would put the output in either of:

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

这篇关于Java 小程序下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆