imageio.IIOException:无法读取输入文件 [英] imageio.IIOException: Can't read input file

查看:3110
本文介绍了imageio.IIOException:无法读取输入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一周前开始使用Java,现在我想在窗口中插入一个图像。
无论我尝试什么,我都会在Eclipse中继续这样做:
javax.imageio.IIOException:无法读取输入文件!

I've started Java a week ago, and now I would like to insert an image into my window. Whatever I try I keep having this in Eclipse: javax.imageio.IIOException: Can't read input file!

package graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import src.Common;

public class Window extends JFrame
{
public class Panel extends JPanel
{

    public void paintComponent(Graphics g)
    {
        Image img; 
        try 
        {
        img = ImageIO.read(new File("/logo.jpg"));
        g.drawImage(img, 0, 0, this);
        } 
        catch (IOException e) 
        {
        e.printStackTrace();
        }

    }
}

public Window(String title, int width, int height)
{
    this.setTitle(title);
    this.setSize(width, height);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setContentPane(new Panel()); 
    this.setVisible(true);
}

}

我认为代码非常自我解释。
我尝试用这个解决问题,< a href =https://stackoverflow.com/questions/13130982/imageio-cant-read-input-file?rq=1>这个,以及那个

I think the code is pretty self-explaining. I tried to solve the problem with this, this, and that .

我想做的是一个桌面程序,我的源存储如下:
training / src / graphics / Window
training / src / src / main

What I'm trying to do is a desktop program, and my sources are stored like that : training/src/graphics/Window training/src/src/main

我做了把我想要阅读的图像放在每个文件夹中,但仍然遇到问题:/

I did put the image I want to read in every folder, and still getting the issue :/

我做错了什么?

编辑终于解决了,这里答案

nIcE cOw给了我链接有帮助。
所以我确实把我的图像放到了一个文件夹中,并改变了访问它们的方式,如链接中所述。

nIcE cOw gave me the link that helped. So I did put my images into a folder, and change the way to access to them, as described in the link.

getClass().getResource("/images/yourImageName.extension");


推荐答案

您是否尝试过使用 new文件(logo.jpg); (没有前导/)?

Have you tried using new File("logo.jpg"); (without the leading /)?

你确定,logo.jpg被复制到你的输出? (某些IDE不会将源目录中的每个文件复制到输出(或目标)目录。)

And are you sure, the logo.jpg is copied to your output? (Some IDEs don't copy every file from your source-directories to your output (or target) directories.)

/src
|-> Window.java
|-> Logo.jpg

变为

/out
|-> Window.class

(请注意,IDE /编译器不会将图像复制到输出目录中所以编译后的代码找不到图像 - 尽管你确实指定了正确的路径)

(Note that the IDE/compiler does not copy the image to your output-directory and so the compiled code cannot find the image - allthough you did specify the correct path)

这篇关于imageio.IIOException:无法读取输入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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