開發者常遇到需驗證遠端伺服器上 PDF 檔案是否存在的需求。許多人嘗試使用 File fileTest = new File("https://example.com/file.pdf"); 搭配 fileTest.exists(),但發現即使檔案確實存在,程式卻不進入 if 區塊。
java.io.File 類別僅適用於本地檔案系統路徑,無法處理 HTTP/HTTPS 等網路協定。當傳入 URL 字串時,File 會將其視為本地絕對路徑(包含冒號、斜線等特殊字元),導致 exists() 永遠回傳 false。
僅檢查回應狀態碼,不下載內容,效能最佳。
// 以 Apache HttpClient 為例
CloseableHttpClient client = HttpClients.createDefault();
HttpHead head = new HttpHead("https://www.augustinianum.eu/roosterwijzigingen/14062012.pdf");
try (CloseableHttpResponse response = client.execute(head)) {
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
// 檔案存在
} else if (status == 404) {
// 檔案不存在
}
}
若伺服器可控,建議提供專用端點:
GET /api/file/exists?filename=14062012.pdf
// 回傳 JSON: { "exists": true }
這能減輕伺服器壓力,避免頻繁存取實體檔案。
若無法控制伺服器,只能嘗試下載並捕捉 FileNotFoundException 或 404 狀態碼。
java.io.File 檢查網路資源。