12
A
回答
22
使用HEAD請求,你可以做這樣的事情:
private static int getFileSize(URL url) {
URLConnection conn = null;
try {
conn = url.openConnection();
if(conn instanceof HttpURLConnection) {
((HttpURLConnection)conn).setRequestMethod("HEAD");
}
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(conn instanceof HttpURLConnection) {
((HttpURLConnection)conn).disconnect();
}
}
}
6
嘗試使用HTTP HEAD方法。它僅返回HTTP標頭。標題Content-Length
應該包含您需要的信息。
2
您是否嘗試過使用URL連接上的getContentLength? 如果服務器響應一個有效的頭文件,你應該得到文件的大小。
但請注意,網絡服務器也可能會以大塊的形式返回文件。在這種情況下,IIRC內容長度方法將返回一個塊的大小(< = 1.4)或-1(> 1.4)。
3
HTTP響應有一個Content-Length頭,所以你可以查詢此值的URLConnection對象。
一旦URL連接已經打開,你可以嘗試這樣的事:
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Map with key=(String) header
// name, value = List of String values for that header field.
// just use the first value here.
String sLength = (String) values.get(0);
if (sLength != null) {
//parse the length into an integer...
...
}
}
0
你可以試試這個..
private long getContentLength(HttpURLConnection conn) {
String transferEncoding = conn.getHeaderField("Transfer-Encoding");
if (transferEncoding == null || transferEncoding.equalsIgnoreCase("chunked")) {
return conn.getHeaderFieldInt("Content-Length", -1);
} else {
return -1;
}
3
接受的答案是容易NullPointerException
,不爲文件> 2GiB工作,幷包含對getInputStream()
的不必要的調用。這裏的固定代碼:
public long getFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
return conn.getContentLengthLong();
} catch (IOException e) {
return -1;
// Or wrap into a (custom, if desired) RuntimeException so exceptions are propagated.
// throw new RuntimeException(e);
// Alternatively you can just propagate IOException, but, urgh.
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
相關問題
- 1. `find'如何計算文件的大小?
- 2. 如何計算音頻文件大小?
- 3. 如何計算protobuf文件大小?
- 4. 計算shell中文件的大小
- 5. 如何從URL中的URL獲取文件大小?
- 6. MongoDB如何計算文檔的大小?
- 7. 在PostgreSQL中計算文件大小
- 8. 如何計算上傳大文件的最佳塊大小
- 9. 如何計算C#中的文件大小
- 10. 如何計算Android中文件的大小
- 11. 如何計算文件中區分大小寫的獨立字
- 12. 計算響應的文件大小?
- 13. 如何計算DB2中表的大小
- 14. 在java中計算S3對象(文件夾)大小
- 15. 在java中,如何計算最大數目減去較小數字的計算?
- 16. 如何在.NET中計算/確定文件夾大小?
- 17. 如何在matlab中計算jpeg2000文件頭大小?
- 18. 從頭文件計算linux核心文件大小
- 19. 如何從點大小計算qfont像素大小
- 20. 如何在C中計算您的計算機的字大小?
- 21. Java文本組件計算自己的首選大小
- 22. Python的`file.read`函數如何計算出文件的大小?
- 23. 計算文本大小
- 24. 如何計算文件夾的大小。 (這個大小必須與Finder一致。)
- 25. 下載前計算文件大小
- 26. 計算大小文件夾python
- 27. 計算文件大小(ASCII值)
- 28. 計算和緩存文件夾大小
- 29. 如何計算MP4文件(MPEG4,H.264)的每分鐘大小?
- 30. 計算Java對象的字節大小
恐怕你將不得不下載文件至少一次以得到確切的大小。 (您可能希望將來存儲,但如果服務器上的文件發生更改,數據將失效) – Nishant
@Nishant這是不正確的。 'HTTP HEAD'請求會返回有關您執行'HTTP GET'請求時會得到的信息的信息,該請求應包含返回請求的大小。你當然可以做'HEAD'請求並解析響應。 – Thor84no
啊,好的。很高興知道。謝謝@ Thor84no – Nishant