Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - imageio.IIOException: Can't read input file

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);
}

}

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

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 :/

What did I do wrong?

EDIT Finally solved, here the answer

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");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

becomes

/out
|-> Window.class

(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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...