0x77D
0x77D

Reputation: 1574

Java InputStream NullPointerException with InputStream

I've got two methods in a class:

  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);
        }
  }

The line commented in the second method is the problem, if I put all in the same method I can download the song without problems, but not if I separate them.

Any ideas? I would like to have them separated to reuse getSongStream.

Upvotes: 0

Views: 5668

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503869

The problem is that you're swallowing exceptions in getSongStream and returning null. Don't do that - let the exception propagate up, possibly having wrapped it in another form... so declare that your method can throw (say) IOException. Your downloadSong method should probably declare that it can throw IOException too. Note that you should have finally blocks to make sure you close your streams appropriately even if an exception is thrown.

It's almost always a bad idea to catch an exception, write it out to standard output and then proceed as if everything is okay.

Upvotes: 1

Related Questions