2017-08-09 710 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

相關問題