Java小程序下载文件 [英] Java Applet Download File
本文介绍了Java小程序下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想建立一个Java小程序下载文件到客户机。作为Java应用此code工作得很好,但是当我尝试作为一个applet它什么都不做。我已经签署了.jar文件和我没有得到任何安全错误讯息
在code是:
进口java.io. *;
进口java.net *。
进口的javax.swing *。
公共类printFile扩展JApplet的{公共无效的init(){尝试{
在java.io.BufferedInputStream中=新java.io.BufferedInputStream中(新
的java.net.URL(http://www.google.com).openStream());
java.io.FileOutputStream中的FOS =新java.io.FileOutputStream中(google.html您);
java.io.BufferedOutputStream回合=新的BufferedOutputStream(FOS,1024);
字节的数据[] =新的字节[1024];
而(in.read(数据,0,1024)> = 0)
{
bout.write(数据);
}
bout.close();
附寄();
}赶上(IOException异常IOE){
}
}
}
谁能帮助?
解决方案
的FileOutputStream FOS =新的FileOutputStream(google.html您);
修改成:
文件USERHOME =新的文件(System.getProperty(的user.home));
文件pageOutput =新的文件(USERHOMEgoogle.html您);
FOS的FileOutputStream =新的FileOutputStream(pageOutput); //见下文替代
在理想情况下,你会把输出中的任何一种:
- A 子目录(也许是基于主类的包名 - 以避免碰撞)
的user.home
的。的user.home
是用户应该能够读取和放的地方;创建文件。 - 由最终用户指定使用的
的JFileChooser
帮助的路径。
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
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:
- 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. - A path as specified by the end user with the help of a
JFileChooser
.
这篇关于Java小程序下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文