杰瑞科技汇

Java如何下载服务器文件到本地?

Java 下载服务器文件到本地

在Java中,有几种方法可以从服务器下载文件到本地,以下是几种常见的实现方式:

Java如何下载服务器文件到本地?-图1
(图片来源网络,侵删)

使用HttpURLConnection(Java标准库)

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
    public static void downloadFile(String fileUrl, String savePath) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 检查HTTP响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Server returned HTTP response code: " + responseCode);
            }
            // 创建输出流
            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(savePath)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("文件下载成功: " + savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String fileUrl = "http://example.com/path/to/file.zip";
        String savePath = "C:/downloads/file.zip";
        downloadFile(fileUrl, savePath);
    }
}

使用Apache HttpClient(更强大的HTTP客户端)

首先需要添加依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

然后使用以下代码:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class HttpClientDownloader {
    public static void downloadFile(String fileUrl, String savePath) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(fileUrl);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try (InputStream inputStream = entity.getContent();
                         FileOutputStream outputStream = new FileOutputStream(savePath)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                    // 确保完全消耗响应内容
                    EntityUtils.consume(entity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String fileUrl = "http://example.com/path/to/file.zip";
        String savePath = "C:/downloads/file.zip";
        downloadFile(fileUrl, savePath);
    }
}

使用Java NIO(适用于大文件)

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class NioDownloader {
    public static void downloadFile(String fileUrl, String savePath) {
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL)
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileUrl))
                .build();
        Path path = Paths.get(savePath);
        try {
            HttpResponse<Path> response = client.send(
                    request, 
                    HttpResponse.BodyHandlers.ofFile(path)
            );
            System.out.println("文件下载成功: " + savePath);
            System.out.println("响应状态码: " + response.statusCode());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String fileUrl = "http://example.com/path/to/file.zip";
        String savePath = "C:/downloads/file.zip";
        downloadFile(fileUrl, savePath);
    }
}

带进度条的下载(示例)

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class ProgressDownloader {
    public static void downloadWithProgress(String fileUrl, String savePath) {
        JFrame frame = new JFrame("下载进度");
        JProgressBar progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        frame.add(progressBar);
        frame.setSize(300, 100);
        frame.setVisible(true);
        new Thread(() -> {
            try {
                URL url = new URL(fileUrl);
                URLConnection connection = url.openConnection();
                int fileSize = connection.getContentLength();
                try (InputStream inputStream = connection.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(savePath)) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    int totalBytesRead = 0;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        int progress = (int) ((totalBytesRead * 100) / fileSize);
                        SwingUtilities.invokeLater(() -> progressBar.setValue(progress));
                    }
                }
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(frame, "下载完成!");
                    frame.dispose();
                });
            } catch (IOException e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(frame, "下载失败: " + e.getMessage());
                    frame.dispose();
                });
            }
        }).start();
    }
    public static void main(String[] args) {
        String fileUrl = "http://example.com/path/to/file.zip";
        String savePath = "C:/downloads/file.zip";
        downloadWithProgress(fileUrl, savePath);
    }
}

注意事项

  1. 错误处理:实际应用中应该添加更完善的错误处理
  2. 大文件处理:对于大文件,考虑使用NIO或分块下载
  3. 认证:如果需要认证,可以添加适当的请求头
  4. 超时设置:为连接设置合理的超时时间
  5. 断点续传:如果需要支持断点续传,需要处理Range请求头

选择哪种方法取决于你的具体需求:

  • 简单下载:使用HttpURLConnection
  • 更复杂的HTTP需求:使用Apache HttpClient
  • Java 11+:使用Java NIO HttpClient
  • 需要UI反馈:使用Swing或JavaFX实现进度条
Java如何下载服务器文件到本地?-图2
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇