21xrx.com
2024-09-20 00:50:06 Friday
登录
文章检索 我的文章 写文章
如何使用Java将文件下载到指定文件夹
2023-06-19 00:41:18 深夜i     --     --
Java 下载文件 指定文件夹

在Java编程中,有时需要将文件从网络下载到指定的文件夹。在本文中,我们将通过代码实例演示如何使用Java下载文件到指定文件夹。

我们需要使用Java中的URLConnection和InputStream类来连接URL并下载文件。以下是实现此过程的示例代码:


import java.net.URL;

import java.net.URLConnection;

import java.io.*;

public class FileDownloader {

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

    URL url = new URL(fileUrl);

    URLConnection connection = url.openConnection();

    InputStream downloadStream = connection.getInputStream();

    byte[] buffer = new byte[1024];

    int length;

    OutputStream outputStream = new FileOutputStream(new File(saveDir + File.separator + connection.getHeaderField("Content-Disposition").split("=")[1].replaceAll("\"", "")));

    while ((length = downloadStream.read(buffer)) != -1) {

      outputStream.write(buffer, 0, length);

    }

    outputStream.close();

    downloadStream.close();

    System.out.println("文件已经成功下载到 " + saveDir);

  }

  public static void main(String[] args) {

    try {

      downloadFile("https://example.com/file.pdf", "/home/user/Downloads");

    } catch (IOException e) {

      e.printStackTrace();

    }

  }

}

在以上代码中,我们将文件下载到目录“/home/user/Downloads”,并在控制台上输出“文件已经成功下载到 /home/user/Downloads”的消息。我们可以将这些参数作为方法的参数来进行更改和调整。

  
  

评论区

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