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

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

问题描述

使用 ImageIO.write() API 调用,当我传递一个不存在的路径,如 "\\abc\abc.png" 时,我得到 NullPointerException.我故意传递不存在的路径来测试某些东西,但我得到的不是 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.createOutputStreamInstance 吞下了 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;
}

唯一的解决方案是在尝试使用 ImageIO 之前验证路径.

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

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

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