2013-07-22 31 views
0

如果在具有該URL的遠程服務器上存在文件,如何檢入Java?如果是,則下載該文件。檢查具有URL的遠程服務器上是否存在文件

這是我的代碼示例 - 它打開指定的URL,然後創建I/O流以複製由URL指定的文件。但最終它沒有按照它應該做的那樣工作。

URL url = new URL(" //Here is my URL");  
url.openConnection();  
InputStream reader = url.openStream();  
FileOutputStream writer = new FileOutputStream("t");  
byte[] buffer = new byte[153600];  
int bytesRead = 0;  
while ((bytesRead = reader.read(buffer)) > 0)  
{  
    writer.write(buffer, 0, bytesRead);  
    buffer = new byte[153600];  
}  
writer.close();  
reader.close(); 
+1

404怎麼樣沒有找到錯誤 –

+0

對於HTTP,如果沒有找到文件,你可能會得到404響應, – Vicky

+1

緩衝區不需要在while循環內重新分配。 –

回答

2

這將做到這一點

public static boolean exists(String URLName){ 
    try { 
     HttpURLConnection.setFollowRedirects(false); 
     // note : you may also need 
     //  HttpURLConnection.setInstanceFollowRedirects(false) 
     HttpURLConnection con = 
     (HttpURLConnection) new URL(URLName).openConnection(); 
     con.setRequestMethod("HEAD"); 
     return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
    } 
1

發送HEAD請求到服務器以檢查該文件在所有腦幹。

import java.net.*; 
import java.io.*; 

    public static boolean fileExists(String URL){ 
    try { 
     HttpURLConnection.setFollowRedirects(false); 
     HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); 
     con.setRequestMethod("HEAD"); 
     if(con.getResponseCode() == HttpURLConnection.HTTP_OK) 
      return true; 
     else 
      return false; 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
     } 
    } 
0

如果文件不存在url.openConnection()將FileNotFoundException異常,你可以捕獲它。除此之外,你的代碼似乎沒問題,但在我看來,使用BufferedInputStream/BufferedOuputStream和按字節讀/寫將使它更清潔。

相關問題