Why can't I read any of my resources in a jar file?

For an application I was developing, I wanted to create a Binary File using the following code:
DataInputStream in = null;
        try {
            File file = new File(name);
            in = new DataInputStream(
                    new BufferedInputStream(
                        new FileInputStream(file)));
        } catch (FileNotFoundException e) {
            System.out.println("Non-existential File.");
            System.exit(0);
}I am using Netbeans 6.5.1., and it groups my projects so that there are folders for build, src, dist, nbproject inside the project folder. The application that I am developing is a graphics demo that requires the use of several text files to represent the maps, so I wanted to read them using a FileInputStream.
I kept this file, "islandmap.txt", in the src folder in my project. In the method above, I coded my program so that the "name" would be "src\islandmap.txt", and it read from the file perfectly. However, I needed to compile it to a Jar file too. After doing that, the program no longer functioned. I remembered when I used a tutorial long ago that used
URL url = getClass().getClassLoader().getResource(fileName) ... in order to get the directory of the files. That made sense, because a person who is running the program via Java Webstart or a Jar Executable would definitely not have the parts of the program located in the same directory, so the code is used to find where the java program is. However, I realized something...
File file = new File( - constructor - )There are four constructors for files, and I only think I could use two. The first is using a string, like I have done before with "src\islandmap.txt." Now, the URL url = getClass().getClassLoader().getResource(fileName) part, it was used before to locate a URL in order to open a buffered image. The constructor for File does not support URLs, but instead supports URIs.I tried converting between the two, changing a URL into a string, and producing a URI from the string. But it did not work, giving me an error that URI was not hierarchical. And that's when I realized that they were certainly not interchangable.
More specifically, here is my code as of now:
public boolean loadMap(String mapName) {
        String path = "src/islandmap.txt";   //This is where the map files are stored
        mapName = getClass().getClassLoader().getResource(path).getPath(); //getPath changes the URL into a String
        DataInputStream in = null;
        try {
            File file = new File(mapName);
            in = new DataInputStream(
                    new BufferedInputStream(
                        new FileInputStream(file)));
             //code to actually read from the file goes here
        } catch (FileNotFoundException e) {
            System.out.println("Non-existential File.");
            System.exit(0);
        } finally {
             //close in
}So that is my problem now. I am stuck. For my purposes, I basically must use a stored text file within my jar, but I don't know how to read it. It distresses me that normally, I already know how to open images that are located inside my src folder using URLs, but not any other file requiring a File class to be wrapped within a Buffered Writer/Reader. Could somebody please assist me with this, or suggest an alternative that would also fall under my conditions? I would appreciate it so much. Thank you.
Edited by: celestialsalt on Dec 6, 2009 5:29 PM
Edited by: celestialsalt on Dec 6, 2009 5:49 PM

Start with
URL url = getClass().getClassLoader().getResource(fileName)Then observe that URL has a [openStream()|http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()] method that will give you an InputStream. Since you are reading text you might want to create an InputStreamReader from which you can do your reading much like you used the FileReader before when you were working with a File.
Class also has a [getResourceAsStream()|http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)] which combines the first two steps into one. Ie use getResource() as you mentioned when you want to get a URL that some other class will use to read (eg an image) or use getResourceAsStream() when you are going to do the reading yourself.

Similar Messages

  • For the first time, I downloaded a podcast in the podcast app by clicking on the cloud icon. Now, every single play button for all of my podcast episodes is grayed out. Why can't I play any of my podcasts any more?

    For the first time, I downloaded a podcast in the podcast app by clicking on the cloud icon. Now, every single play button for all of my podcast episodes is grayed out. Why can't I play any of my podcasts any more?

    Greetings Heather,
    After reading your post, it sounds like you are experiencing an error with the Podcasts app. You may want to consider restarting the device first, and then resetting if that does not work. This article provides detailed instructions for Restarting, and Reseting:
    Turn your iOS device off and on (restart) and reset
    How to restart
    Press and hold the Sleep/Wake button on the top of your device until the red slider appears. Then drag the slider to turn your device completely off.
    After the device turns off, press and hold the Sleep/Wake button again until you see the Apple logo.
    How to reset
    You should reset your device as a last resort and only if you can't restart it.
    To reset, press and hold both the Sleep/Wake and Home buttons for at least 10 seconds, until you see the Apple logo.
    Thank you for contributing to Apple Support Communities,
    BobbyD

  • HT4623 Why can't I install any apps keeps saying that my session has timed out

    Why can't I install any apps it keeps saying my session has timed out

    Thanks for your suggestion Ned01, I tried this as a last ditch attempt, unfortunatly it made no difference in my case, but i'm pleased it did for you. However, because you reminded me to have another go at this problem, i tried something else (which i'd unsucsessfuly tried before), that is, i deleted the 'CLICK & SAVE " a/c i'd set up recently,  and reverted to my previous payment me and would you know it , this time it worked !! I set up a trail purchase and it worked.
    It seems to me that other poeple with this problem have to solve it by trail and error, but thank you for your help.Sandystone..

  • Why can't I open any of the attachments in my email

    Why can't I open any of the attachments in my email.  I did not have this problem before

    What is your operating system?
    What is your email client?
    What is your Reader version?
    What exactly means "can't"?
    Does this happen for any attachments, or just PDF files?

  • Why can I not delete any emails on iPhone. 5?

    Why can I not delete any emails on my iphone5?

    Thx. That seems to have solved my problem. I don't know but just all of a sudden when I opened an emal there was no option at the bottom.  After doing as you suggested, now all the options are back. Quite confusing to me. I do appreciate your suggestion and fix.

  • Why can I not see any of my music purchases, I have not changed my ID or account details

    Why can I not see any of my music purchases, I have not changed my ID or account details?

    Hi,
    Please enable Speakers in Playback devices as follows:
    1. Right click speaker icon (right hand corner)
    2. Select Playback devices
    3. Right click Speakers
    4. Enable it and set as Default
    5. Click Apply/Ok
    Regards.
    BH
    **Click the KUDOS thumb up on the left to say 'Thanks'**
    Make it easier for other people to find solutions by marking a Reply 'Accept as Solution' if it solves your problem.

  • In Dreamweaver CC why can i not get any workspace options? Where do I find 'Draw AP div'?

    In Dreamweaver CC why can i not get any workspace options? Where do I find 'Draw AP div' or any of my 'designer' tools?

    Insertion of APDivs/Layers are deprecated in CC. Historically, APDivs caused many, many problems for people who didn't understand they were not intended to be used as a primary layout tool.  Look at FluidGrid Layouts.
    http://blogs.adobe.com/dreamweaver/
    Nancy O.

  • Why can't i play any of my music in my library or my home sharing music?

    Why Can't i play any my music from my library or home sharing files?

    Greetings Heather,
    After reading your post, it sounds like you are experiencing an error with the Podcasts app. You may want to consider restarting the device first, and then resetting if that does not work. This article provides detailed instructions for Restarting, and Reseting:
    Turn your iOS device off and on (restart) and reset
    How to restart
    Press and hold the Sleep/Wake button on the top of your device until the red slider appears. Then drag the slider to turn your device completely off.
    After the device turns off, press and hold the Sleep/Wake button again until you see the Apple logo.
    How to reset
    You should reset your device as a last resort and only if you can't restart it.
    To reset, press and hold both the Sleep/Wake and Home buttons for at least 10 seconds, until you see the Apple logo.
    Thank you for contributing to Apple Support Communities,
    BobbyD

  • Why can't I read a book purchased through iPhone ibook app on my MacBook Pro?

    Why can't I read a book purchased through iPhone ibook app on my MacBook Pro? Also, is there any way to print pages from book?

    In general if you want to read paid-for ebooks on your Mac, you need to buy them from one of the other sources like Kindle, Nook, Kobo, or Googlebooks and use the free OS X and iOS reader apps which they provide instead of iBooks.

  • TS1702 Why can't I update any of my apps

    Why can't I update any of my apps on my IPhone 4s, a message comes up saying cannot connect to iTunes Store

    "Cannot Connect to iTunes store "  usually means your internet service provider doesn't allow itunes to load and they 've filtered it , try VPN and it'll surely works .

  • Why can't I make any calls on facetime, the call drops after saying connecting.

    Why can't I make any calls on facetime, the call drops after saying connecting for a few seconds. I'm using an iphone 5, 32 GB on IOS 6.0.1 over 3G network in Muscat, Oman. Just to be clear, I was able to make facetime call in Muscat about a week ago.

    If this user to user forum could not help you with your issue, contact Apple to get your Device serviced or looked at.
    http://www.apple.com/contact/

  • Why can't I read posts?

    Why can't I read posts? Is there an outage on the forum site or is my browzer doing something to block links? I can see topics and lists of posts, but only blank windows open when I click on a post. Of course, I won't be able to read your answer should this problem be at my end and it persists ... if a system thing, somebody should post a notice at the top level of the forum ... thanks.

    I dusted-off my old PB-1400 and now I can read the posts.
    I'm in the process of trouble-shooting a failed G4, so I had signed-in with a Win-PC running 98SE and IE v. 6. I had already tried clearing the cache and made sure cookies cleared, then enabled, etc. Still can't see posts. I downloaded Firefox 1.5 and tried that, still can't see posts. I have no problem with any other sites online that require special cookies, scripts, etc.
    Perhaps the Apple discussion site saw the machine was running Win98 and snubbed me??? If not that, there must be some wierd script or something. Go figure.

  • Why can't I play any videos on Firefox Mobile?

    Why can't I play any videos on Firefox Mobile? I know that currently Firefox Mobile does not support Flash, but mp4 videos will not play either.

    I fixed it by rebooting, now everything works. Thanks Demo, for your help.

  • Why can't I get any sound to come from my phone unless I put it on speaker phone?

    Why can't I get any sound to come from my phone unless I put it on speaker?

    Do you still have the original plastic shipping cover on the face of the iPhone?  Or any kind of screen protector that covers the speaker ear hole.  That will block the sound.
    My wife experienced this.
    Also if you still have the shipping plastic on the back, it will cause the camera flash to spill back into the camera lense spoiling your pictures.

  • Why can't I download any more apps on my iPad mini

    Why can't I download any more apps on my ipad mini

    Try deleting the waiting app then reset your device. Press and hold the Home and Sleep buttons simultaneously until the Apple logo appears. Let go of the buttons and let the device restart. See if that fixes your problem.

Maybe you are looking for

  • No show-up of a dialogue box again for me to enter S/N of Acrobat 9 Pro;and pic distort in Photoshop

    I have two problems: 1. The Acrobat 9 Pro is a separate DVD and I did again just insert this DVD. Still no dialogue box appears for me to enter the serial number (even though I have got the     serial number) for installing. I fail to install Acrobat

  • User exits for Material Master in ECC 6.0

    Hello, We would like to have a function for checking descriptions when we are saving a material in the material master. We are today running R/3 on release 4.6C and as I understad there are no user exits at that point for this release. We are going t

  • LV2009: Graph- Copy Data moves/removes cursors

    Using a right click->Copy Data seems to move or remove cursors from the image copied to the clipboard.  Anyone know of a workaround that doesn't involve screen cap and edit? PrtScn result: Copy Data result: Other results show the cursor changing its

  • Databaseadapter & file adapter

    Hello evrybody, i am using 10.1.3.1.0 version. i would like to take the data from the table (oracle 10g) and saved in .txt file. It is a local system. i used database adapter (select operation) i used receive activity then i used file adapter(selecte

  • Right Click Event on Flash

    Hello I am making a CD based CBT. I need to do action on mouse right click something like on<mouse right click> { play(); Thanks Mohammed sunely