已经知道了一个文件的URL,如何用JAVA下载并保存这个文件?

解决方案 »

  1.   

    用JAVA下载?response.sendRedirect(url);
    非html,gif等ie能打开的文件会自动提示下载。
      

  2.   

    URL url;BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(url)));
    用bis将文件保存。
      

  3.   

    上面这个例子,如果文件URL 是个远程的就不行了.
    要用 url.openStream();
    因为url 不一定是本地文件. file:/C:/abc.txt 这种形式,
    也可能是 http://afwef.com/abc.txt 或者 ftp://username:password@host:port/path/file.txt
      

  4.   

    找了一个完整的例子
    public final InputStream getResourceAsStream(String location) throws IOException {
    try {
    // try URL
    URL url = new URL(location);
    logger.debug("Opening as URL: " + location);
    return url.openStream();
    } catch (MalformedURLException ex) {
    // no URL -> try (file) path
    InputStream in = getResourceByPath(location);
    if (in == null) {
    throw new FileNotFoundException("Location '" + location + "' isn't a URL and cannot be interpreted as (file) path");
    }
    return in;
    }
    }
      

  5.   

    public void downloadFile_( String strTempDir , String httpUrl)
        {
            try
            {
                URL url = null;            url = new URL( httpUrl );            BufferedInputStream input = new BufferedInputStream(url.openStream());
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(strTempDir));            byte[] buf = new byte[1024*1024];            int len = input.read(buf, 0, buf.length);
                while (len != -1)
                {
                    out.write(buf, 0, len);
                    len = input.read(buf, 0, buf.length);
                }            input.close();
                input = null;
                out.close();
                out = null;
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }    public void downloadFile() throws IOException
        {
            for( int i = 3290;i < 3292; i++ )
            {
                String strTempDir = "c:\\fonts\\" + String.valueOf(i) + ".rar";            String location = "http://font.flash8.net/download.aspx?app=font&id=";
                location = location + String.valueOf(i);            this.downloadFile_( strTempDir , location );
            }
        }