下载文件

来源:互联网 发布:java采购管理系统 编辑:程序博客网 时间:2024/06/01 09:14
import java.net.*;
import java.io.*;
public class URLConnectionDemo{
    public static void main(String[] args)throws Exception{
        URL url = new URL("http://www.scp.edu.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");
        URLConnection uc = url.openConnection();
        String fileName = uc.getHeaderField(6);
        fileName = URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
        System.out.println("文件名为:"+fileName);
        System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");
        String path = "D:"+File.separator+fileName;
        FileOutputStream os = new FileOutputStream(path);
        InputStream is = uc.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
        os.close();
        is.close();
        System.out.println("下载成功,文件保存在:"+path);
    }
}
0 0
原创粉丝点击