1

Currently I have code like this in my program:

BufferedImage ReadPicture = null;
            try {
                ReadPicture = ImageIO.read(new File("C:/Users/John/Documents/NetBeansProjects/Program5/build/classes/Program5/Pictures/TestPicture.png"));
            } catch (IOException e) {
            }

If I compile my file to a jar and give it to someone else, the program does not work as the classpath is specific to my computer. How can I change how I access files/images so that it works on all computers?

2 Answers2

1

For ImageIO in particular, if you always want to read an image from the classpath, without regard to what the classpath actually is, then you can do this:

BufferedImage readPicture = null;
URL imageUrl = getClass().getClassLoader().getResource(
        "/Program5/files/Pictures/TestPicture.png");
// Or
// InputStream imageStream = getClass().getClassLoader().getResourceAsStream(
//         "/Program5/files/Pictures/TestPicture.png");

// null if not found

try {
    readPicture = ImageIO.read(imageUrl);
    // null if the image format is unrecognized
} catch (IOException e) {
    // ...
}

That relies on the fact that ImageIO can obtain images via URLs. This approach can be used even if the image is packaged in a Jar file, along side your classes (or not).

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

You can add a folder in your project named files or anything you want.You can make sub-directories in it and arrange files in that.They will be available when you will share it with others.In the code below,"." represents working directory.So make sure the directory structure you are providing,is correct.Try something like this.

BufferedImage ReadPicture = null;
try {
         ReadPicture = ImageIO.read(new File("./files/Pictures/TestPicture.png"));

     } catch (IOException e) {
     }

See Also

Community
  • 1
  • 1
RockAndRoll
  • 2,247
  • 2
  • 16
  • 35
  • Reading from a path relative to `.` is error-prone. The whole VM has only one sense of the current working directory (i.e. `.`) and it does not necessarily bear any particular relationship to the location of any given class or resource file. – John Bollinger Sep 25 '15 at 20:12