如何从Java下载URL中的文件

时间:2021-07-15 15:26:53

I have a URL, http://www.skype.com/en/download-skype/skype-for-windows/downloading/. If I run this URL in Chrome the EXE file of Skype starts downloading. However if I write the code to download the file I am not able to do so. Here is my code:

我有一个网址,http://www.skype.com/en/download-skype/skype-for-windows/downloading/。如果我在Chrome中运行此URL,则Skype的EXE文件开始下载。但是,如果我编写代码来下载文件,我无法这样做。这是我的代码:

public static void saveFile(URL url, String file) throws IOException {
    System.out.println("opening connection");
    InputStream in = url.openStream();
    FileOutputStream fos = new FileOutputStream(new File(file));

    System.out.println("Reading file...");
    int length = -1;
    byte[] buffer = new byte[1024]; // Buffer for portion of data from

    // Connection
    while ((length = in.read(buffer)) > -1) {
        fos.write(buffer, 0, length);
    }

    fos.close();
    in.close();
    System.out.println("File was downloaded");
}

public static void main(String args[])
{
    try
    {
         URL url = new URL("http://www.skype.com/en/download-skype/skype-for-windows/downloading/");
         String fileName = "C:/SETUP/skype.exe";
         saveFile(url, fileName);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

1 个解决方案

#1


3  

You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.

你指的是错误的网址。在http://www.skype.com/en/download-skype/skype-for-windows/downloading/,您只能获得可以下载exe的HTML页面。

The direct URL that refers to the exe is: http://get.skype.com/go/getskype

引用该exe的直接URL是:http://get.skype.com/go/getskype

#1


3  

You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.

你指的是错误的网址。在http://www.skype.com/en/download-skype/skype-for-windows/downloading/,您只能获得可以下载exe的HTML页面。

The direct URL that refers to the exe is: http://get.skype.com/go/getskype

引用该exe的直接URL是:http://get.skype.com/go/getskype