您的位置:首页 > 编程语言 > Java开发

java 通过 URL 类和 URLConnection类 以及输入流实现文件下载功能

2011-11-03 22:30 891 查看
package udp;

import java.net.* ;

import javax.swing.* ;

import java.awt.event.*;

import java.io.* ;

public class Download

{

public static void main(String[]args)

{

JFrame jf=new JFrame("XiaoWei DownLoad Software") ;

jf.addWindowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

System.exit(0); //退出程序

}

});

jf.setSize(600,400);

jf.setLocation(200,300);

JPanel p=new JPanel() ; //面板默认是FlowLayout布局管理器

final JTextField j=new JTextField("Please Input DownLoad Address In This Area",40) ;

JLabel l=new JLabel("请输入下载地址:") ;

p.add(l);

p.add(j);

jf.getContentPane().add(p,"North");

final JTextArea t1=new JTextArea() ;

jf.getContentPane().add(t1,"Center");

JButton b=new JButton("DownLoad") ;

jf.getContentPane().add(b,"South") ;

b.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

String s=j.getText(); //如果要在内部类中使用局部变量的话 要把局部变量设置为final类型 最终类型

try

{

String line=System.getProperty("line.separator") ;//获得与平台无关的换行

URL url=new URL(s);

URLConnection u=url.openConnection() ; //打开连接 获得URLConnection类的对象

t1.append("目标主机:" +url.getHost());

t1.append(line);

t1.append("主机缺省端口:"+url.getDefaultPort());

t1.append(line);

t1.append("目标类型:"+u.getContentType()) ;

t1.append(line);

t1.append("对象大小"+u.getContentLength());

InputStream in=u.getInputStream() ;//打开 输入流

InputStreamReader r=new InputStreamReader(in); //字节流到字符流转换的桥梁

BufferedReader br=new BufferedReader(r) ; //连接到bufferreader提供读取一行数据的功能

FileOutputStream fos=new FileOutputStream("D:\\1.html") ; //假如我们下载网页文件

String str ; //用String的好处是 读取到多少个字符 就会开辟多少的空间

while ((str=br.readLine())!=null) {

fos.write(str.getBytes()); //因为读取一行文本会忽略换行回车 那么实际读取的文件会小 所以应该加上 我们应该使用与系统无关的回车换行

fos.write(line.getBytes()); //最后写的文件比 实际文件大2个字节 是因为 我们在最后一次多写入了 回车 换行 2个字节

}

fos.close(); //关闭文件流

br.close();

r.close();

in.close(); //使用完流要关闭

}

catch(Exception xe)

{

xe.printStackTrace();

}

}

});

jf.show();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: