我在一个类中有两个方法:
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。
发布于 2011-04-19 17:18:50
问题是您在getSongStream中吞噬了异常并返回null。不要这样做-让异常向上传播,可能已经将其包装在另一种形式中...所以声明您方法可以抛出(比方说) IOException。您的downloadSong方法应该声明它也可以抛出IOException。请注意,您应该具有finally块,以确保即使抛出异常,也可以适当地关闭流。
捕获异常,将其写入标准输出,然后继续处理,就好像一切正常一样,这几乎总是一个糟糕的主意。
https://stackoverflow.com/questions/5714102
复制相似问题