21xrx.com
2025-04-02 21:50:55 Wednesday
文章检索 我的文章 写文章
使用Java轻松下载文件
2023-06-10 08:20:31 深夜i     --     --
Java 下载 文件保存

我喜欢使用Java,因为它是一种可靠的编程语言,能够让我轻松创建高质量的软件应用程序。

Java语言具有强大的编程能力,其可移植性和安全特性使其成为众多开发者的首选。在我的开发中,我通常会下载Java的最新版本,以确保我能够使用最新的功能和功能。

以下是Java的一个简单示例,展示了如何使用Java下载和保存文件:

import java.io.*;
import java.net.*;
public class FileDownloader {
  public static void main(String[] args) {
    String fileUrl = "https://example.com/file.pdf";
    String saveDir = "/home/user/downloads/";
    try {
      URL url = new URL(fileUrl);
      HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
      int responseCode = httpConn.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        if (disposition != null) {
          int index = disposition.indexOf("filename=");
          if (index > 0) {
            fileName = disposition.substring(index + 10, disposition.length() - 1);
          }
        } else {
          fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());
        }
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + fileName;
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);
        int bytesRead = -1;
        byte[] buffer = new byte[4096];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
          outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        System.out.println("File downloaded.");
      } else {
        System.out.println("Error downloading file.");
      }
      httpConn.disconnect();
    } catch (IOException ex) {
      System.out.println("Error with file download: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
}

通过上述代码,我们可以非常简单地下载文件到本地。只需要提供文件的URL和本地保存目录即可。

  
  

评论区

    相似文章