2011-04-19 68 views
0

我有一類兩種方法:的Java的InputStream NullPointerException異常隨同InputStream

private static InputStream getSongStream(String ip, String id){ 
     try { 
     URL url = new URL("http://"+ ip + "/" + Client.streamphp); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 

     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     wr.write(data); //Data is a simple Http Post that is know to work 
     wr.flush(); 
     wr.close(); 

     return conn.getInputStream(); 

    } catch (MalformedURLException badurl) { 
     System.out.println(badurl); 
     return null; 
    } catch (IOException noconnection) { 
     System.out.println(noconnection); 
     return null; 
    } 
    } 

    public static void downloadSong(String ip, String id, String path){ 
     InputStream rd = Client.getSongStream(ip, id); 
     try { 
      OutputStream stream = new FileOutputStream(new File(path)); 

      byte[] buffer = new byte[4096]; 
      int len; 
      while ((len = rd.read(buffer)) > 0) { //Here I get NullPointerException 
      stream.write(buffer, 0, len); 
      } 
      stream.close(); 
      rd.close(); 

    } catch (IOException noconnection) { 
      System.out.println(noconnection); 
     } 
    } 

在第二種方法評價該生產線的問題,如果我把所有相同的方法,我可以下載歌曲,而不問題,但如果我將它們分開,則不會。

任何想法?我想讓它們分開以重用getSongStream。

+0

也許RD是空的...檢查此 – Tobias 2011-04-19 09:16:49

回答

1

問題是,你在吞嚥異常getSongStream並返回null。不要這樣做 - 讓異常傳播,可能已經用另一種形式包裝了它......所以聲明你的方法可以拋出(比如說)IOException。你的downloadSong方法可能應該聲明它也可以拋出IOException。請注意,即使發生異常,您也應該終止塊以確保適當地關閉流。

這幾乎是總是一個壞主意,以捕獲一個異常,寫出標準輸出,然後繼續進行,如果一切正常。