Как исправить пустое имя при получении имени файла из URL - PullRequest
0 голосов
/ 30 июня 2019

Я пытаюсь создать метод, который получает URL и возвращает имя файла.Я пытался использовать в другом методе System.out.println(Utility.getName("www.site.com/myfile.zip"));, но он возвращает пустой.Как я могу это исправить?

public class Utility {

    public static String getName(String fileURL)
            throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
        String fileName = "";

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {

            String disposition = httpConn.getHeaderField("Content-Disposition");

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                        fileURL.length());
            }
        }
        return fileName;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...