使用Java代码通过URL下载文件

6
我正在尝试用Java编写代码,让用户提供一个网址链接,然后程序会下载该网页并将其保存在特定位置,就像网页上的“另存为”选项一样。请问有人能帮我吗?谢谢。

1
你能说一下你已经做了什么吗?你卡在哪个点上了? - Vincent Ramdhanie
3个回答

9

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

这是一个指向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 {
        }
    }
}

它完全正常工作。

请检查您的代码,也许语句fileDownload(args[i], args[0]);中的参数应该交换。 - Daniele

5
你可以使用Java URL API获取URL上的输入流,然后通过文件的输出流将其读取并写入其中。
请参见从URL读取数据, 写入文件

1

看一下HtmlParser。它有一些功能可以帮助您从网页中提取资源。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接