0

I am trying this code in java:

  try
  {
    String url = "http://url.com/file.ext";
    InputStream myInputStream = getClass().getResourceAsStream(url);
    ByteArrayOutputStream myByteArrayOutputStream = new ByteArrayOutputStream();
    byte[] arrayOfByte = new byte[1024];
    int i;
    while ((i = myInputStream.read(arrayOfByte)) != -1)
    {
      myByteArrayOutputStream.write(arrayOfByte, 0, i);
    }
  }
  catch (Exception e)
  {
      System.err.println(e);
      System.err.println(e.getMessage());
      System.err.println(e.getLocalizedMessage());
      System.err.println(e.getCause());
      System.err.println(Arrays.toString(e.getStackTrace()));
      e.printStackTrace();

  }

It compiles fine but it throws an exception, this is the console output:

java.lang.NullPointerException
null
null
null
[myclass.init(myclass.java:32), sun.applet.AppletPanel.run(Unknown Source), java.lang.Thread.run(Unknown Source)]
java.lang.NullPointerException
    at myclass.init(myclass.java:32) <- Line 32 is "while ((i = myInputStream....."
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

What could be causing the exception?

0

2 Answers 2

3

Actually taking a second look, your InputStream myInputStream = getClass().getResourceAsStream(url); Doesn't make sense, instead use

Url url = new Url("http://url.com/file.ext");
UrlConnection urlCon = url.openConnection();
InputStream input = urlCon.getInputStream();

That should grab the bytes correctly

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - this is correct IF that URL is indeed correct. If that's wrong, you still won't get those bytes. I'd recommend checking the InputStream before you use it.
3

The InputStream is clearly null. It's the only object that's dereferenced at that line.

getResourceAsStream() uses the class loader to search for the named resource in the CLASSPATH. The URL that you provided is guaranteed to NOT be in your CLASSPATH, so there's no mystery here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.