簡體   English   中英

在Java中下載文件時如何獲取文件名?

[英]How to get file name while downloading a file in Java?

我有FileDownloader類,可以從google驅動器下載文件,然后這些文件可以由其他類使用。 我還需要以某種方式提取文件名。 問題是下面的解決方案適用於直接鏈接,但是例如當使用bit.ly縮短鏈接時,該解決方案將不起作用...請您告知我如何更改代碼以獲取正確的文件名?

public class FileDownloader {

private static final int BUFFER_SIZE = 4096;


public static void downloadFile(String fileURL, String saveDir)
        throws IOException {
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    // checking HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename*=UTF-8''");

            if (index > 0) {
                fileName = disposition.substring(index + 17,
                        disposition.length());
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                    fileURL.length());
        }

        System.out.println("Content-Type = " + contentType);
        System.out.println("Content-Disposition = " + disposition);
        System.out.println("Content-Length = " + contentLength);
        System.out.println("fileName = " + fileName);

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        System.out.println("File downloaded");
    } else {
        System.out.println("No file to download. Server replied HTTP code: " +  responseCode);
    }
    httpConn.disconnect();
}

使用Java API從任何HTTP URL獲取文件詳細信息的備用代碼:

URL url =新URL(“ http://www.example.com/somepath/filename.extension ”);

    System.out.println(FilenameUtils.getBaseName(url.getPath())); 

// 文檔名稱

    System.out.println(FilenameUtils.getName(url.getPath())); 

// filename.extension

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM