如何在Java中下载文件时获取文件名?

时间:2017-08-09 14:00:24

标签: java http

我有FileDownloader类从谷歌驱动器下载文件,而这些文件可以被其他类使用。我还需要以某种方式提取文件名。问题是下面这个解决方案适用于直接链接,但是当链接缩短时,它不起作用,例如... 您能否告诉我如何更改代码以获取正确的文件名?

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();
}

1 个答案:

答案 0 :(得分:0)

使用Java API从任何HTTP URL获取文件详细信息的备用代码:

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

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

// filename

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

// filename.extension