2017-08-09 112 views
-1

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

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

尝试更加具体在何处的错误发生。看看如何创建一个[mcve] –

+0

有没有其他的解决方案如何获得你正在下载的文件的文件名? – Boris

回答

0

替换代码来获得使用Java API从任何HTTP 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

+0

谢谢。我会尝试。请告诉我这也适用于间接链接(因为我在你的描述中看到了“filname.extension”)? – Boris

相关问题