Results 1 to 3 of 3
  1. #1
    Pojahn_M's Avatar
    Pojahn_M is offline Senior Member
    Join Date
    Mar 2011
    Location
    Sweden
    Posts
    197
    Rep Power
    4

    Default Read file from a jar

    I have created a program(with GUI) and made a jar of it, so its now a program. The gui have a background image, which I load using this code:
    Java Code:
    backgroundImage = ImageIO.read(new File("mainwindow.png"));
    Placing the image in the root of the jar file give me run time error(cannot load image).
    If I place the image outside the jar, in the same directory as the jar, the image will be loaded(this is unwanted, I want to the image in the jar and read it from there).
    What do I do?

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: Read file from a jar

    Retrieve the URL to the file inside the jar by using the getResource("my file") method of the class object (you can call getClass() on an instance, or use MyClass.class syntax). Then pass the URL to ImageIO. Read the API on these methods for more information on how to specify the path of the file relative to a class in a different package.

  3. #3
    Pojahn_M's Avatar
    Pojahn_M is offline Senior Member
    Join Date
    Mar 2011
    Location
    Sweden
    Posts
    197
    Rep Power
    4

    Default Re: Read file from a jar

    thanks, works now.
    very useful information.

    Java Code:
    backgroundImage = ImageIO.read(Components.class.getResource("mainwindow.png"));

Similar Threads

  1. Replies: 1
    Last Post: 08-05-2011, 09:21 PM
  2. Replies: 2
    Last Post: 05-11-2009, 10:07 AM
  3. Replies: 0
    Last Post: 02-11-2009, 09:53 AM
  4. Replies: 5
    Last Post: 02-05-2009, 10:28 AM
  5. How to read a text file from a Java Archive File
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 09:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •