21xrx.com
2024-09-20 06:08:28 Friday
登录
文章检索 我的文章 写文章
JAVA开发教程:实现文件下载并选择下载位置
2023-06-18 22:36:23 深夜i     --     --
JAVA开发 文件下载 缓冲器

在JAVA开发过程中,经常需要实现文件下载的功能。本文将介绍如何使用JAVA代码实现文件下载,并且还可以让用户选择下载文件的位置。

示例代码:


import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.URL;

import java.net.URLConnection;

public class DownloadFile {

  public static void main(String[] args) throws IOException {

    String fileURL = "https://example.com/file.zip";

    String saveDir = "C:/Downloads";

    downloadFile(fileURL, saveDir);

  }

  public static void downloadFile(String fileURL, String saveDir) throws IOException {

    URL url = new URL(fileURL);

    URLConnection conn = url.openConnection();

    BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

    String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);

    String saveFilePath = saveDir + "/" + fileName;

    FileOutputStream out = new FileOutputStream(saveFilePath);

    BufferedOutputStream bout = new BufferedOutputStream(out, 1024);

    byte[] buffer = new byte[1024];

    int byteRead = 0;

    while ((byteRead = in.read(buffer, 0, 1024)) != -1) {

      bout.write(buffer, 0, byteRead);

    }

    bout.close();

    out.close();

    in.close();

    System.out.println("Downloaded Successfully.");

  }

}

在代码中,我们首先定义了文件的URL和保存位置,然后调用`downloadFile()`方法来实现下载。在该方法中,我们使用`URLConnection`来连接到该文件的URL,并从中获取`InputStream`。然后我们使用`FileOutputStream`将文件写入磁盘。

这里需要注意,如果没有指定`BufferedInputStream`和`BufferedOutputStream`,下载会非常慢并且可能会出现丢失的数据块。因此,我们使用了这两个缓冲器来提高下载速度。

最后,在成功下载文件后,我们打印了一条消息来提示用户下载成功。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复