2013-08-19 185 views
-1

我需要檢查,如果adresse上的文件存在,然後我下載它。它工作正常,直到它到達一些不存在的文件。 try-catch塊並不能很好地解決問題。當我打開連接(InputStream)時,它嘗試下載它,但失敗並轉到「catch」。但它並沒有關閉它的自我。下一次,我訪問具有相同IP的方法,它崩潰和賽斯 - 在同一個IP的連接太多(2)關閉連接 - InputStream

摘要:

,直到它到達錯誤的住址,它工作正常

時到達錯誤的住址,它去「抓」,但犯規關閉它的自我,它不能再被連接

public boolean exists(String URLName) throws IOException { 
    boolean result = false; 
    URL url = new URL(URLName); 
    try { 
     input = url.openStream(); 
     System.out.println("SUCCESS"); 
     result = true; 
     input.close(); 
    } catch (Exception e) { 
     input.close(); 
     System.out.println("FAIL"); 
    } 
    return result; 
} 

我已經試過各種方法,但如果沒有一些特殊的技巧,它不會工作。請有誰能幫我解決這個問題?

+0

因爲這是客戶端代碼它不應該失敗或塊剛過一個連接失敗。這是許多失敗連接仍在TIME_WAIT階段的情況嗎? –

回答

1

爲什麼不直接使用Finally塊並關閉它中的所有連接......?

+0

這應該是一條評論... –

+0

我認爲它也是一個解決方案。不是嗎? –

+0

當我嘗試關閉連接時,它不會打開,它會顯示nullpointerex ... – fatevil

1

我將使用finally塊關閉我的InputStream並重構代碼以使用URLConnection代替。

例子:

public boolean exists(String URLName) throws IOException { 
    boolean result = false; 
    URLConnection connection = null; 
    InputStream input = null; 
    try { 
    connection = new URL(URLName).openConnection(); 
     input = connection.getInputStream(); 
     System.out.println("SUCCESS"); 
     result = true; 
    } catch (Exception e) { 
     System.out.println("FAIL"); 
    } finally { 
     if (input != null) { 
      input.close(); 
     } 
    } 
    return result; 
} 
+0

不錯的一個..我以爲我只是去說,而不是說明如何去做.. –

+0

此外,這段代碼是醜陋的....它需要更多的重構... –

+0

當然,它更多的是複製和粘貼當他們提出問題時,人們應該這樣做。 –

0

嘗試使用Apache的HttpClient http://hc.apache.org/httpcomponents-client-ga/index.html的新版本中,使用此代碼:

HttpClient httpClient = new HttpClient(); 
GetMethod get = new GetMethod(url); 
     try{ 
httpClient.executeMethod(get); 


     return get.getResponseBodyAsString(); 


    } catch (HttpException clP_e) { 

     throw new IOException(clP_e); 

    } finally { 

     get.releaseConnection(); 

    } 
+0

,但它與ftp協議工作? – fatevil

+0

不,它並不是你必須使用的:http://commons.apache.org/proper/commons-net/ – Felquir