gpt4 book ai didi

写入字节数组时出现java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-01 16:38:49 26 4
gpt4 key购买 nike

我正在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();

}

编译正常,但抛出异常,这是控制台输出:

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)

什么可能导致异常?

最佳答案

实际上再看一下,你的InputStream myInputStream = getClass().getResourceAsStream(url);没有意义,而是使用

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

这应该正确抓取字节

关于写入字节数组时出现java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6286732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com