Java获取下载文件名称

在Java中,有时候我们需要从网络上下载文件,并且还要获取这个文件的名称。本文将介绍如何使用Java来获取下载文件的名称,并提供了相应的代码示例。

1. 使用HttpURLConnection下载文件

在Java中,我们可以使用HttpURLConnection类来下载文件。下面是一个简单的示例代码:

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {

    public static void main(String[] args) {
        String fileUrl = "
        String savePath = "C:/downloads/";
        
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取文件名
                String fileName = getFileName(connection);
                
                // 创建文件输出流
                FileOutputStream outputStream = new FileOutputStream(savePath + fileName);
                
                // 获取文件输入流
                InputStream inputStream = connection.getInputStream();
                
                // 读取文件内容并写入输出流
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                // 关闭流
                outputStream.close();
                inputStream.close();
                
                System.out.println("文件下载成功!");
            } else {
                System.out.println("文件下载失败!错误代码:" + responseCode);
            }
            
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 获取文件名
    public static String getFileName(HttpURLConnection connection) {
        String disposition = connection.getHeaderField("Content-Disposition");
        
        if (disposition != null && disposition.indexOf("filename=") != -1) {
            return disposition.substring(disposition.indexOf("filename=") + 9);
        }
        
        return null;
    }
}

上述代码通过HttpURLConnection发送GET请求下载文件,并且通过getFileName方法获取文件名。

2. 使用OkHttp下载文件

除了HttpURLConnection,还可以使用第三方库OkHttp来下载文件。下面是一个使用OkHttp下载文件的示例代码:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileDownloader {

    public static void main(String[] args) {
        String fileUrl = "
        String savePath = "C:/downloads/";
        
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(fileUrl).build();
        
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                // 获取文件名
                String fileName = getFileName(response.header("Content-Disposition"));
                
                // 创建文件输出流
                FileOutputStream outputStream = new FileOutputStream(savePath + fileName);
                
                // 获取响应体
                ResponseBody responseBody = response.body();
                
                // 读取文件内容并写入输出流
                outputStream.write(responseBody.bytes());
                
                // 关闭流
                outputStream.close();
                
                System.out.println("文件下载成功!");
            } else {
                System.out.println("文件下载失败!错误代码:" + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取文件名
    public static String getFileName(String header) {
        if (header != null && header.indexOf("filename=") != -1) {
            return header.substring(header.indexOf("filename=") + 9);
        }
        
        return null;
    }
}

上述代码使用OkHttp发送GET请求下载文件,并通过getFileName方法获取文件名。

3. 文件下载流程图

下面是文件下载的流程图:

st=>start: 开始
e=>end: 结束
op1=>operation: 发送HTTP请求
op2=>operation: 获取响应
op3=>operation: 获取文件名
op4=>operation: 创建文件输出流
op5=>operation: 读取文件内容并写入输出流
op6=>operation: 关闭流

st->op1->op2->op3->op4->op5->op6->e

4. 结论

本文介绍了如何使用Java来获取下载文件的名称,并提供了使用HttpURLConnection和OkHttp的示例代码。通过这些方法,我们可以轻松地下载文件并获取文件名,以便后续处理。

希望本文对您有所帮助!