不过,他是对的。例如,这段代码:
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。
为什么异常被如此残酷地压制,我不知道。代码片段是
try {
return new FileImageOutputStream((File)output);
} catch (Exception e) {
e.printStackTrace();
return null;
}
唯一的解决方案是在尝试使用 ImageIO之前验证路径。