Java ImageIO: Exception

In my application, I tried to save BufferedImageto a PNG file using ImageIO. The file is selected by the user, so I need to respond to errors that may occur (for example, the user is trying to save in a place where he does not have write permission). However, I can’t catch IOExceptionwhat is happening.

The following code shows the problem. Trying to save to "/ foo" should throw an exception for most users on * nix systems, since they do not have write permissions to the root directory.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class IOTest {

    public static void main(String[] args) {
        BufferedImage img = new BufferedImage(640, 480,
                BufferedImage.TYPE_INT_RGB);
        try {
            File f = new File("/foo");
            ImageIO.write(img, "png", f);
        } catch (IOException e) {
            System.out.println("Caught IOException!");
        }
    }
}

However, no exception was found. Output:

    java.io.FileNotFoundException: /foo (Permission denied)
    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 IOTest.main(IOTest.java:16)
Exception in thread "main" java.lang.NullPointerException
    at javax.imageio.ImageIO.write(ImageIO.java:1538)
    at IOTest.main(IOTest.java:16)

Note that this FileNotFoundExceptionis a subclass IOException, so it should be caught. The second blocking block also did not help:

catch (FileNotFoundException e) {
    System.out.println("Caught FileNotFoundException!");
} catch (IOException e) {
    System.out.println("Caught IOException!");
}

What am I doing wrong?

+5
4

ImageIO. , File ImageIO.write, FileOutputStream write.

, ImageIO.write. 1530:

stream = createImageOutputStream(output);

1538:

stream.close();

createImageOutputStream, , null.

+6

, ImageIO.write IOException, NullPointerException. , , RuntimeException...

, , , .

+4

It seems to ImageIO.write()wrap FileNotFoundExceptionin NullPointerException.

You should catch NullPointerExceptionor better verify the existence of the file before calling ImageIO.write().

0
source

In appearance, this FileNotFoundException is handled in javax.imageio.ImageIO.write, and this failure throws an exception using a null pointer. Try checking file permissions before trying to save them!

0
source

All Articles