使用“ ImageIO.write()” API调用我得到NullPointerException [英] With "ImageIO.write()" API call I get NullPointerException

查看:665
本文介绍了使用“ ImageIO.write()” API调用我得到NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 ImageIO.write() API调用,当我传递不存在的路径时,会得到 NullPointerException \\abc\abc.png 。我故意通过不存在的路径来测试某些东西,但没有得到 FileNotFoundException ,而是得到了 NPE 。这是为什么?

With ImageIO.write() API call, I get NullPointerException when I pass a non-existent path like "\\abc\abc.png". I pass the non-existent path purposely to test something but instead of getting FileNotFoundException, I get NPE. Why is that?

ImageIO.write() API应该抛出 IOException 但不要解释为什么我得到 NPE

ImageIO.write() API is supposed to throw IOException but don't why I get NPE.

我使用异常消息字符串在消息中显示它框,但在这种情况下 NPE.getLocalizedMessage()返回空字符串,因此弹出框为空,上面只有一个图标。

I use exception message string to show it in a message box to user but in this case NPE.getLocalizedMessage() returns empty string and hence the popup is empty with just an icon on it.

推荐答案

对。例如,这段代码:

He is right, though. For example, this code:

public static void main(String[] args) throws IOException {
 BufferedImage image = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
 File out = new File("\\\\ABC\\abc.png");
 ImageIO.write(image, "png", out);
}

给予

java.io.FileNotFoundException: \\ABC\abc.png (The network path was not found)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:233)
at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:69)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:55)
at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:419)
at javax.imageio.ImageIO.write(ImageIO.java:1530)
at javaapplication145.JavaApplication145.main(JavaApplication145.java:24)
Exception in thread "main" java.lang.NullPointerException
at javax.imageio.ImageIO.write(ImageIO.java:1538)
at javaapplication145.JavaApplication145.main(JavaApplication145.java:24)

原因是 FileImageOutputStreamSpi.createOutputStreamInsta因为吞下FileNotFoundException,然后当 ImageIO.write 试图关闭未打开的流时,NPE出现。

The reason is that FileImageOutputStreamSpi.createOutputStreamInstance swallows the FileNotFoundException and then the NPE comes when ImageIO.write tries to close a stream that didn't open.

为什么这么残酷地抑制异常,我不知道。代码片段是

Why the exception is suppressed so brutally, I don't know. The code fragment is

try {
 return new FileImageOutputStream((File)output);
} catch (Exception e) {
 e.printStackTrace();
 return null;
}

唯一的解决方案是验证路径 before 尝试使用ImageIO。

The only solution is to verify the path before attempting to use ImageIO.

这篇关于使用“ ImageIO.write()” API调用我得到NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆