无法读取输入文件,IOException

时间:2013-08-15 07:02:08

标签: java image file-io ioexception

我试图在Jform的面板中制作图像按钮数组。为此我想通过给出路径来添加图像,但这里是无法读取输入文件的IO异常。错误发生在

Exception in thread "main" javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(ImageIO.java:1301)
    at serverui.ImageArray.main(ImageArray.java:38)

代码如下:     package serverui;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageArray {
    Image[] images;

    public ImageArray(Image[] images) {
        this.images = images;
    }

    private JPanel getContent() {
        JPanel panel = new JPanel(new GridLayout(0,2,5,5));
        panel.setBackground(Color.green.darker());
        for(int i = 0; i < images.length; i++) {
            ImageIcon icon = new ImageIcon(images[i]);
            JLabel label = new JLabel(icon, JLabel.CENTER);
            panel.add(label);
        }
        return panel;
    }

    public static void main(String[] args) throws IOException {

        String prefix = "images/";
        String[] ids = { "desktopactive", "desktopoff" };
        String ext = ".png";
        Image[] images = new Image[ids.length];
        for(int i = 0; i < images.length; i++) {
            String path = prefix + ids[i] + ext;
            images[i] = ImageIO.read(new File(path));
        }

        ImageArray app = new ImageArray(images);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(app.getContent());
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
    }
}

3 个答案:

答案 0 :(得分:1)

按如下方式更改您的代码,路径问题

   String prefix = "D:\\TestFolder\\";
    String[] ids = { "Capture"};
    String ext = ".png";
    Image[] images = new Image[ids.length];
    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        images[i] = ImageIO.read(new File(path));
    }

这样它对我有用。有时,如果在prefix驱动器(操作系统安装分区)中提供C作为文件夹,则由于权限问题,您可能无法读取该文件。以上其他内容将解决您的问题。

答案 1 :(得分:0)

您应确保两个文件都存在。

    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        File file = new File(path);
        if (!file.exists()) {
            throw new IllegalArgumentException("file "+file+" does not exist");
        }
        images[i] = ImageIO.read(file);
    }

确保images与您当前的目录相关。如果您将images放在类路径中,则可以使用:

    for(int i = 0; i < images.length; i++) {
        String path = prefix + ids[i] + ext;
        URL url = ImageArray.class.getResource(path);
        if (url == null) {
            throw new IllegalArgumentException("url "+url+" does not exist");
        }
        images[i] = ImageIO.read(url);
    }

答案 2 :(得分:0)

嗯,这取决于你的平台,如果这确实在Windows上。然后你需要把它改成\ on

String prefix = "images/"

如果需要,您可以创建一个if语句,根据操作系统修改字符串。您获得操作系统的方式是通过

System.getProperty("os.name")