57

I want to have a place to store my image files to use in my Java project (a really simple class that just loads an image onto a panel). I have looked everywhere and cannot find how to do this. How do I do this?

I have tried adding a new folder to the project, adding a new class folder to the project, and adding a new source folder to the project. No matter what I do, I always get a IOException. The folders always say they are on the build path, so I'm not sure what to do.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PracticeFrame extends JFrame{

private static BufferedImage image;
Thread thread;

public PracticeFrame() {
    super();
    setPreferredSize(new Dimension(640,480));
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
}

public static void main (String[] args) {
    PracticeFrame pframe = new PracticeFrame();
    try {
        image = ImageIO.read(new File("/islands.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    JPanel panel = new JPanel() {
        @Override
        protected void  paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image,0,0,null);
        }
    };

    panel.setBackground(Color.BLUE);
    panel.repaint();
    pframe.add(panel);


}


}

EDIT: Something that worked for me, and I have no idea why, was adding the main/res/ folder as a class folder and then removing it. I ran it while the /main/res/ was part of the build path as a class folder and it still didn't work. When i added it, i got a popup that told me something about excluded filters. But when i removed the folder from the libraries in the build path, and changed my file path to:

image = ImageIO.read(new File("src/main/res/islands.png"));

I at least stopped getting the IOException thrown. I must not be adding the image to the panel correctly, because it's not showing up, but at least it found the file (I think).

Lii
  • 11,553
  • 8
  • 64
  • 88
redeagle47
  • 1,355
  • 4
  • 14
  • 26

8 Answers8

80

When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder enter image description here

add "my-resource.txt" file inside the new folder. Then in your code:

    InputStream res =
    Main.class.getResourceAsStream("/my-resource.txt");

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(res));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();
Frederic
  • 2,015
  • 4
  • 20
  • 37
Lautaro Cozzani
  • 1,798
  • 13
  • 15
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – Julian F. Weinert Jan 14 '15 at 03:28
  • 3
    I think this is a right answer, the author really doesnt know about how to add resources to a proyecto. He need to know how to open in from the code. – Lautaro Cozzani Jan 14 '15 at 03:48
  • You should add more informations. Please explain what the OP did wrong and why (especially *how*) your code fixes the problem. – Julian F. Weinert Jan 14 '15 at 03:51
  • 1
    Ok, in the original example, readagle try to open the file with File class, then you have to provide a path starting from the executable is running, whether or not a resource. If you open a resource with getResourceAsStream(), it will be open from project resources folder. – Lautaro Cozzani Jan 14 '15 at 03:56
  • 2
    Great information, now go ahead, edit your post and put the info there ;-) – Julian F. Weinert Jan 14 '15 at 03:59
  • but this isn't what my question is about. I'm trying to figure out how to add resources folders to Eclipse projects, and that means any project, not just this one. I just used this as an example because it happened to be what I was working on at the time. – redeagle47 Jan 14 '15 at 04:25
  • getClass().getResource("/file.txt") has worked for me – Bahadir Tasdemir Dec 23 '15 at 10:29
  • what does build path mean? i downvoted because i have no idea where that is - can you be more specific? – bharal Jan 23 '17 at 03:57
  • Why does /myfile.txt work and not /resources/myfile.txt ? – Baked Inhalf Jan 15 '18 at 14:15
  • It is about how to create a file named resource, not how to mark a file as a resource one. – Gangnus May 31 '19 at 10:24
16

To answer your question posted in the title of this topic...

Step 1--> Right Click on Java Project, Select the option "Properties" Step 1--> Right Click on Java Project, Select the option "Properties"

Step 2--> Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder" Select "Java Build Path" from the left side menu, make sure you are on "Source" tab, click "Add Folder"

Step 3--> Click the option "Create New Folder..." available at the bottom of the window Click the option "Create New Folder..." available at the bottom of the window

Step 4--> Enter the name of the new folder as "resources" and then click "Finish" Enter the name of the new folder as "resources" and then click "Finish"

Step 5--> Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"
Now you'll be able to see the newly created folder "resources" under your java project, Click "Ok", again Click "Ok"

Final Step --> Now you should be able to see the new folder "resources" under your java project
Now you should be able to see the new folder "resources" under your java project

Suresh
  • 1,491
  • 2
  • 22
  • 27
  • 11
    ...And it is set as a SOURCE folder, not a RESOURCE one. That is not an answer to the question. – Gangnus May 31 '19 at 10:21
5

Build Path -> Configure Build Path -> Libraries (Tab) -> Add Class Folder, then select your folder or create one.

BHA Bilel
  • 331
  • 5
  • 14
  • 1
    This answer worked for me! None of the answers above worked! None of the answers in any other thread worked either! – FriskySaga Mar 16 '20 at 02:58
4

After adding a resource folder try this :

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("test.png");

try {
    image = ImageIO.read(input);
} catch (IOException e) {
    e.printStackTrace();
}
Rami Del Toro
  • 1,130
  • 9
  • 24
1

If aim is to create a resources folder parallel to src/main/java, then do the following:

Right Click on your project > New > Source Folder
Provide Folder Name as src/main/resources
Finish
vinsinraw
  • 2,003
  • 1
  • 16
  • 18
1

Right click on project > Click on properties > Java Build Path > Source > Add Folder

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mandeep Singh Gill
  • 1,145
  • 9
  • 5
1

If you have multiple sub-projects then you need to add the resources folder to each project's run configuration class path like so:

class path

Ensure the new path is top of the entries and then the runtime will check that path first for any resources (before checking sub-paths)

rupweb
  • 3,052
  • 1
  • 30
  • 57
-1

Try To Give Full path for reading image.

Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));

your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java

If the object of your class is created at end your code works fine for me and displays the image

// PracticeFrame pframe = new PracticeFrame();//comment this

new PracticeFrame().add(panel);
jones j alapat
  • 931
  • 3
  • 13
  • 26