通过使用java代码传递URL来下载文件 [英] Download file by passing URL using java code

查看:333
本文介绍了通过使用java代码传递URL来下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在java中编写代码,其中用户提供url链接,程序采用url链接并按原样下载网页并保存在特定位置。同样可以保存为...选项可用网页。

I am trying to write a code in java in which user provide a url link and the program take url link and download a web page as it is and save at particular location..same as save as... option available on webpage.

请任何人帮助我

提前致谢

推荐答案

//示例网址: http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip

import java.io.*;
import java.net.*;


public class UrlDownload {
    final static int size = 1024;

    public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
        OutputStream outStream = null;
        URLConnection uCon = null;

        InputStream is = null;
        try {
            URL url;
            byte[] buf;
            int byteRead, byteWritten = 0;
            url = new URL(fAddress);
            outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));

            uCon = url.openConnection();
            is = uCon.getInputStream();
            buf = new byte[size];
            while ((byteRead = is.read(buf)) != -1) {
                outStream.write(buf, 0, byteRead);
                byteWritten += byteRead;
            }
            System.out.println("Downloaded Successfully.");
            System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void fileDownload(String fAddress, String destinationDir) {
        int slashIndex = fAddress.lastIndexOf('/');
        int periodIndex = fAddress.lastIndexOf('.');

        String fileName = fAddress.substring(slashIndex + 1);

        if (periodIndex >= 1 && slashIndex >= 0 && slashIndex < fAddress.length() - 1) {
            fileUrl(fAddress, fileName, destinationDir);
        } else {
            System.err.println("path or file name.");
        }
    }

    public static void main(String[] args) {
        if (args.length == 2) {
            for (int i = 1; i < args.length; i++) {
                fileDownload(args[i], args[0]);
            }
        } else {
        }
    }
}

它完全正常工作。

这篇关于通过使用java代码传递URL来下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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