Browse files and dirs in the JAR-file

Hi! I'm stuck with a problem concerning browsing a JAR file to find all images, fonts and sound clips. I think this is a pretty straight-forward task, except when I consider that the file I want to browse, is the same file the browser is stored in and running from. I have searched for hours on the internet now, and I still haven't figured out a way to be able to browse my JAR file.
Here is the code I use when I'm not running my project in a JAR-file:
     * Load and cache all files (*.ttf, *.png and *.wav) from the resource-directory
    public void loadResources() throws FileNotFoundException {
        // log available VRAM
        log.println("Available VRAM before loading resources: " + graphicsDevice.getAvailableAcceleratedMemory() + " bytes", Log.INIT);
        // determine whether or not we are dealing with the contents of a jar-file
        jar = getClass().getResource("").getProtocol().startsWith("jar");
        // browse all directories
        long start, end;
        int loadTime = -1;
        start = System.nanoTime();
        browseDirectory(".." + separator + "resources");
        end = System.nanoTime();
        loadTime = Math.abs((int)(end - start) / 1000000);
        resourcesLoaded = true;
        // log
        log.println("Resources loaded in " + loadTime + " ms", Log.INIT);
        // log available VRAM
        log.println("Available VRAM after loading resources: " + graphicsDevice.getAvailableAcceleratedMemory() + " bytes", Log.INIT);
     * Browse a directory and load and cache all it's files
     * @param path The directory to browse
    private void browseDirectory(String path) {
        // log
        log.println("Browsing directory: " + path.replaceFirst("\\W*", ""), Log.INIT);
        try {
            if (jar) {
                // TODO: enable JAR-browsing by getting the input stream from the JAR-file, then browse through all entries
                throw new RuntimeException("Cannot browse JAR-files yet!");
            else {
                File dir = new File(getClass().getResource(path).toURI());
                // browse through the directory
                String[] files = dir.list();
                File file;
                for (String name: files) {
                    file = new File(dir.getAbsolutePath() + separator + name);
                    // if this is a new sub-directory, browse it
                    if (file.isDirectory()) browseDirectory(path + separator + file.getName());
                    // otherwise, add the file
                    else addFile(path, name);
        catch (Exception e) { e.printStackTrace(); }
    } But, as you may see, I need a similar code to browse the JAR-file....please help me!
lhk

I worked it out by trying and failing:
      * Browse the JAR-file and load all it's relevant files
     private void browseJar() {
          try {
               // convert the resource directory path to a JAR-compatible path
               String jarDir = dir.replaceAll("\\" + separator, String.valueOf(jarSeparator));
               // get the jar-file and it's entries
               Enumeration<JarEntry> entries = new JarFile(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).entries();
               // browse the contents of the file
               JarEntry entry;
               int nameIndex;
               String name = null;
               String path = null;
               while (entries.hasMoreElements()) {
                    // get the entry
                    entry = entries.nextElement();
                    // we only process relevant entries
                    if (entry.getName().startsWith(jarDir)) {
                         nameIndex = entry.getName().lastIndexOf(jarSeparator);
                         name = entry.getName().substring(nameIndex + 1);
                         // if we find a new directory, we get it's path
                         if (entry.isDirectory()) {
                              path = entry.getName().substring(jarDir.length(), nameIndex);
                              if (path.startsWith(String.valueOf(jarSeparator))) path = path.substring(1) + jarSeparator;
                              // log (the system-compatible path)
                              log.println("Browsing directory: " + dir + separator + path.replaceAll(String.valueOf(jarSeparator), "\\" + separator), Log.INIT);
                         // otherwise, we add the resource
                         else addFile(path, name);
          catch (Exception e) { e.printStackTrace(); }
     }As may be seen in the code, I discovered that the regular file separator could not be used in jar paths, which I found strange. I tried a lot to make the regular separator work, but couldn't manage it. Anyway, this code works for me.

Similar Messages

  • A .txt in jar,and dont kown the jar's absolute path,how to read it

    I have help.txt and HelpReader class in a jar,and dont kown the jar's absolute path,how to let
    HelpReader class can find help.txt and read it??
    thanks

    Make sure the jar is in your program's classpath. Then use something likeInputStream help = this.getClass().getResourceAsStream("/help.txt");to read the file. Exactly what you would use depends on where in the jar file the help.txt file is located.

  • How to get a file in the same dir with the jar-executable

    Hi,
    I need to read/write a file that exists in the same directory with the jar-executable. How can i do that? I think that when i specify no path for the file, the file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and the file are.
    Thanx in advance

    Hi,
    I need to read/write a file that exists in the same
    directory with the jar-executable. How can i do that?
    I think that when i specify no path for the file, the
    file has to be in current path. (Is that right?)
    Note: I do not know in which directory the jar and
    the file are.
    Thanx in advance
    When you specify no path for the file, the file has to be in the directory where the virtual machine was started. ( the directory the java command was invoked in .)
    If you can't control the directory in which the vm is started, but you know the name of the .jar file you can do the following. This trick takes advantage of the fact that if you are using classes in a jar file, the name of the jar file must be in your classpath.
    public static String getPathOfJar( String nameOfJar )
    throws Exception
    StringTokenizer st = new StringTokenizer(
    System.getProperty( "java.class.path" ) ,
              System.getProperty( "path.separator" ) );
    String jarfile = "";
    while ( st.hasMoreTokens() )     
    String token = st.nextToken();
    if ( token.indexOf( nameOfJar ) > -1 )
    jarfile = token;
    break;
    if ( jarfile.equals("") ) throw new Exception( "Jar not found in classpath" );
    String path = jarfile.substring( 0 , jarfile.indexOf( nameOfJar ) );
    return path;
    //To open a file in the same directory as the sun archive tools.jar
    File f = new File( getPathofJar( "tools.jar" ) + "someFile.txt" );

  • Uneraseable files and dirs inside the trash can

    I,
    I have got some items in the trash can that wher I try to emply it, I get an error message saying that the can't be erased because they are being used. I have turned off the computer several times but the same thing happens.
    Is there a solution for this?

    Hi,
    I'm terribly sorry for the wrong info!
    In addition, be very carefully while using The Terminal and you can always use whatis and man to understand the command you are gonna use. Example:
    Last login: Thu Dec 16 21:20:40 on ttys000
    The-Universe:~ LS$ whatis sudo
    sudo(8) - execute a command as another user
    The-Universe:~ LS$ whatis rm
    rm(1), unlink(1) - remove directory entries
    The-Universe:~ LS$ man rm
    RM(1) BSD General Commands Manual RM(1)
    NAME
    rm, unlink -- remove directory entries
    SYNOPSIS
    rm [-dfiPRrvW] file ...
    unlink file
    DESCRIPTION
    The rm utility attempts to remove the non-direc-
    tory type files specified on the command line. If
    the permissions of the file do not permit writing,
    and the standard input device is a terminal, the
    user is prompted (on the standard error output)
    for confirmation.
    The options are as follows:
    -d Attempt to remove directories as well
    as other types of files.
    -f Attempt to remove the files without
    prompting for confirmation, regardless
    For man, press space bar to continue the manual or q to quite.
    Cheers.
    Message was edited by: (n_n)

  • Need to disable the clearing of browsing history and what is the "about:config" function for it?

    I am working on an Group Policy Administrative template for Wetdog.exe, and it's awesome by the way. Just want to know what function to use (listed in "about:config" url) so i can turn this feature off entirely.
    I don't want my users deleting browsing history, or have any ability to view it either.
    Still, i want the browser to keep at least 30 days of history.
    This is EASILY accomplished in Internet Explorer via GPO, but not so much in Mozilla with wetdog.exe and it's admin templates. I am using Windows Server 2003 enterprise edition R2 on 2 domain controllers, and Windows XP Professional SP3 client workstations with Mozilla 3.6.3 and the latest version of Wetdog.exe and it's admin templates.
    Any help would be much appreciated!!!
    == This happened ==
    Every time Firefox opened
    == My boss decided that we need to keep browsing history locked out of our existing 700+ workstations ==
    == Troubleshooting information ==
    just need to disable the "history" button, the "tools\clear recent history" button, and "tools\options\privacy tab\history"

    It can be annoying, but I think their motivation is good.  They are trying to make things better for their customers and I think they have, even though sometimes it is annoying.  I think it would be nice if they would advise us when the pages are going to be down for maintenance,  In the mean time, you could have another E mail account so you can always get access to your E mail.

  • 8.1 console (browser IE and Netscape) crashes the computer

    When starting a console for WLS 8.1.1 (Administration or Integration) I can work
    a short time until the computer crashes. Mouse hangs, a beep rang out and nothing
    work. The computer has to be rebooted!
    I work with Windows 2000 with Internet Explorer 5.50 and Netscape Version 7.01.
    Java PlugIn is installed. The browser java console shows the system environment:
    Java(TM) Plug-in: Version 1.4.0_01
    Verwendung der JRE-Version 1.4.0_01 Java HotSpot(TM) Client VM
    java.runtime.name = Java(TM) 2 Runtime Environment, Standard Edition
    java.runtime.version = 1.4.0_01-b03
    java.specification.name = Java Platform API Specification
    java.specification.vendor = Sun Microsystems Inc.
    java.specification.version = 1.4
    java.util.prefs.PreferencesFactory = java.util.prefs.WindowsPreferencesFactory
    java.vendor = Sun Microsystems Inc.
    java.vendor.applet = true
    java.vendor.url = http://java.sun.com/
    java.vendor.url.applet = true
    java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
    java.version = 1.4.0_01
    java.version.applet = true
    java.vm.info = mixed mode
    java.vm.name = Java HotSpot(TM) Client VM
    java.vm.specification.name = Java Virtual Machine Specification
    java.vm.specification.vendor = Sun Microsystems Inc.
    java.vm.specification.version = 1.0
    java.vm.vendor = Sun Microsystems Inc.
    java.vm.version = 1.4.0_01-b03
    javaplugin.maxHeapSize = 96m
    Has anyone an idea what/why goes wrong and how the problem could be solved?
    Thanks for any help!

    "petra" <[email protected]> wrote:
    Java(TM) Plug-in: Version 1.4.0_01
    Has anyone an idea what/why goes wrong and how the problem could be solved?Try upgrading your Java Runtime plug-in within Netscape. You're using
    1.4.0 and the latest Sun JRE version is 1.4.2
    (http://java.sun.com/j2se/1.4.2/download.html).
    Hope this works out for you.
    Brian J. Mitchell
    Systems Administrator, MIS
    TRX
    6 West Druid Hills Drive
    Atlanta, GA 30329 USA
    http://www.trx.com
    email: [email protected]
    office: +1 404 327 7238
    mobile: +1 678 283 6530

  • When i type a url, it open this url every time "chrome://browser/content/browser.xul" and it open the new window in a tab. Please help

    or when i tri google search, this url is automatically open and open a new window inside a tab.

    Do you have that problem when running in the Firefox SafeMode?<br/> ''A troubleshooting mode.''<br />
    You can open the Firefox 4.0 SafeMode by holding the '''Shft''' key when you use the Firefox desktop or Start menu shortcut. Or use the Help menu item, click on '''Restart with Add-ons Disabled...''' while Firefox is running. <br />
    ''To exit the Firefox Safe Mode, just close Firefox and wait a few seconds before using the Firefox shortcut to open it again.''
    If not, see this: <br />
    http://support.mozilla.com/en-US/kb/troubleshooting+extensions+and+themes

  • Why does my browser freeze and give me the message below when I am in hotmail:

    A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete. Script: https://js2.wlxrs.com/_D/F$Live.SiteContent.Messenger/4.2.59120/release/Microsoft.Live.Core.LocalStorage.FF.js:39

    * "Clear the Cache": Tools > Options > Advanced > Network > Offline Storage (Cache): "Clear Now"
    * "Remove the Cookies" from sites that cause problems: Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in [[Safe Mode]] to check if one of the add-ons is causing the problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]
    * [[Troubleshooting plugins]]

  • ODI - Multi development environment how to share the JAR files

    Hi,
    For some of our functionality, existing KM not sufficient so we created with our own KM and we have called some jave code which we created and place inside lib directory of ODI as a JAR file. there are four people in the development work. so we have four development environment(all are complete installation, i.e while installing we choosing Complete Option).
    One of our developer created the our own KM and he placed the jar file in his own Dev environment's lib Directory. Since four Dev environment shares the some work rep we could see the new KM and all the ODI object in all the dev env. but if we run the the ODI interface which use the new KM from other Dev environment where we dint place the jar we are getting Error.
    if we keep the jar file in all the other three Dev environment's LIB directory then respective interface working.
    here my doubt,   is there any other way to share the JAR file to all the Environment without copying into everywhere?
    Thanks
    Knidhi

    Thanks you verymuch Cezar and Ratish, now almost i got the answer for my question.
    i installed ODI Server into separate machine. it has folder structure as follows
    Directory: D:/ODIServer/oracledi/ has the following subfolder
    1.bin 2.drivers 3.lib 4.tools.
    here i need to keep my Jar files under the lib folder. am i right?
    and bin directory contains only Agent related batch files. (agent.bat, agentscheduler.bat,agentservice.bat,agentstop.bat,agentstart.bat,agentweb.bat and jython.bat and respective .sh files)
    here dont know how to precede the following things
    1. how to configure the Master and Work Repository information with ODI Server?(MR and WR i already created with the help of one the ODI Client)
    2. how to configure the Client machine to Server?
    3. Since ODI Server not having the Topology, how to create the Agent? do i need to use any one of the ODI Client for this task?
    --Thanks
    Knidhi

  • For what ever reason I cannot locate my favorites, and cannot see my web browser on my firefox. My grandson used the computer yesterday and many of the usual thing are missing. Browser bar, favorites tools etc. Can you help

    The line where the browser bar would ordinarily be is just a black space. My favorites list, browsing history and most of the firefox toolbar is missing.

    It sounds like he hid the menu bar. Press either Alt or F10 to temporarily display the menu bar, then in the view menu select Toolbars, then click on "Menu Bar" in the list of toolbars to display it permanently. Active toolbars have a tick by their name. For more details see the [[menu bar is missing]] article.

  • List dirs in a jar

    Hi,
    i need to scan a directory (resources) for files and if there are any files (there are!) - put all file names in a list. All works fine until I pack all class files and the resources dir in a jar file. I need to run the application packed as a jar file.
    Is there any possibility to read a DIRECTORY inside a jar file? I can open files inside the archive, but not directories...
    Any help is appreciated :)
    Thanks in advance,
    Merlin

    Perhaps I did not explained my problem very well...
    what you propose, JProg, is of course correct, but
    what if I don't know the name of the jar file? Can I
    determine during the run time the name of the jar file
    in which the class files and the resources are
    packed?
    Now I find a single resource file like that:
    this.getClass().getResource("resources/text.properties"
    This works fine for files, but not for dirs. If I
    request the URL for a dir inside the jar file
    this.getClass().getResource("resources/");
    I only get a FileNotFoundException: Specified resource
    can not be found.
    How can I determine the name of the jar in which the
    involved class is packed?Hm it's something like this...
    Class anyClassOfTheJar;
    URL jarURL = anyClassOfTheJar.getProtectionDomain().getCodeSource().getLocation();

  • Problem With Loading the jars

    Hello Experts,
    I am facing a problem with loading classes.
    i have written one application which is running on server.in that application want to use certain jars(Classes)and those jars anmes and
    classes inside the jars are same.based on the condition i want to call
    corresponding class.
    can any one suggest the solution
    it's urgent
    any help will be appriciated
    thanks in advance
    With regds
    Bankuru

    Hi Yogee,
    Thanks for ur help.
    i have 4.o jars and 5.1 version jars.depending on the condingtion system must use the corrensponding jar.the problem here is that both jars has same clasees and code inside that one is differnet.
    when i run application with 4.o condition then 5.1 is not working and
    if i run tha application with 5.1 then 4.o is not working.
    can u please suggest the possible solution
    i have deployed these jars in application server
    With Regds
    Bankuru

  • If the setting is "never remember history", and user clear the caches/cookies and logs on a website will the previous setting of the user on the web app persis

    ON the firefox, the setting is set to "Never remember history" .
    I have a web site which sets the default value on the record per page dropdown list to 100 for every tab.
    When I change the value to 5 and then logout. clear the caches/cookies . and then reload the page and then login to the website the value is showing as 5? why is it so? since the default value of the dropdown on fress login should be displayed as 100. I am facing this issue in Firefox 20.0.1 and on Internet explorer its working fine, the default value of the drop down is showing up as "100" . Let me know what behavior is expected on firefox on the above mentioned issue. This relates to firefox browser only.

    Are you sure the setting is stored in an HTTP cookie (regular browser cookie), and not on the server or in some other kind of local storage (e.g., Flash LSO)?

  • Want to open a new browser window and display the html file in locale disk.

    Hi,
    I want to open a new browser window and display the html file in local drive. The below html applet work in local system successfully. But i deploy the same in web server (Tomcat) and try the same in client machine it does not work. Please help.
    Note:
    The class below fileopen.FileOpen.class i make it as a jar and put it in jre\ext folder at the client machine.
    ------------------------------------FileOpen.html(Tomcat)-----------------------------------------------------
    <html>
    <body >
    <applet code="OpenFile.class" archive="loadfile.jar" width="100" height="100">
    <param name="path" value="file://c:/open.html" />
    </applet>
    </body>
    </html>
    -------------OpenFile.java in server(Tomcat)--------------------------------------------
    public class OpenFile extends Applet implements ActionListener{
    String path = "";
    fileopen.FileOpen open = null;
    Button b = null;
    public void init(){
    path = getParameter("path");
    b = new Button("Open");
    b.addActionListener(this);
    add(b);
    public void actionPerformed(ActionEvent ae){
    try
    open = new fileopen.FileOpen(this,path);
    catch (Exception e){
    e.printStackTrace();
    -------------------------------------------FileOpen.java /Client JRE/ext----------------------------------------------------
    package fileopen;
    public class FileOpen
    AppletContext context = null;
    URL url = null;
    public FileOpen(Applet applet,String path)
    try
    if(null != applet){
    context = applet.getAppletContext();
    if (null != path)
    url = new URL(path);
    context.showDocument(url, "_blank");
    }catch(Exception ex)
    ex.printStackTrace();
    Please help to solve this issue very urgent.
    Thanks in advance.
    By,
    Saravanan.K.

    zzsara wrote:
    I want to open a new browser window and display the html file in local drive. ...Did you ever pause to consider how ridiculous that is?
    The best audience for applets is people off the internet. 'People off the internet' might be using a computer that has no (what was it?) 'open.html' in the root of the C: drive. In fact (shock horror) they may not even be running Windows, and would therefore probably have no 'C:' drive at all.
    If you do not intend to distribute this to people off the web, an application makes a lot more sense, but even then, you cannot rely on the document being there unless you 'put it there' (during installation, for instance).
    As the other poster intimated, applets can load documents off the local disk as long as they are trusted. Here is an example*, but note that it is not so rash as to presume any particular path or file, and instead leaves it to the user to choose the document to display.
    * The short code can be seen at SDNShare on the [Defensive Loading of Trusted Applets|http://sdnshare.sun.com/view.jsp?id=2315] post.
    On the other hand, a sandboxed applet can load any document coming from its own server via URL, or get showDocument(URL) to work. In that case, the JRE must recognize that the URL is from its own server, so the best way to form URLs for applet use is via the URL constructor
    new URL(getDocumentBase(), "path/to/open.html");That is how I form the URL in this [ sandboxed example of formatting source|http://pscode.org/fmt/sbx.html?url=/jh%2FHelpSetter.java&col=2&fnt=2&tab=2&ln=0]. Of course, in this case the applet loads the document, then parses the text to draw the formatted version, but the point is that an URL produced this way will work with showDocument(URL).
    I am pretty sure showDocument() in an applet off the internet will work with an URL pointing to a foreign (not its own) server, but it will not be able to load documents off the end user's local disks.
    I suggest a couple of things.
    - Try to express this problem in terms of what feature it is that you want to offer the end user. Your question jumps directly to a bad strategy for achieving ..who knows what? An example of a feature is "Shows the applet 'help' files on pressing F1".
    - A good way to indicate interest in a solution is to offer [Duke stars|http://wikis.sun.com/display/SunForums/Duke+Stars+Program+Overview] to match that interest.
    Edit 1:
    ..and please figure out how to use the CODE tags.
    Edited by: AndrewThompson64 on Sep 12, 2008 11:14 PM

  • When I publish my site on one specific page where i've added {tag_pagecontent} I get the error:Some files on the server may be missing or incorrect. Clear browser cache and try again. If the problem persists please contact website author.

    When I publish my site on one specific page where I've added {tag_pagecontent} I get the error:
    'Some files on the server may be missing or incorrect. Clear browser cache and try again. If the problem persists please contact website author.'
    I'm trying to get a blog module going, I've even deleted the html insert bog with the tag in and re-published which then I don't get the error but as a result no blog either. But then I add the tag in again and publish the error comes back. I've used the dev console and it says that my musicians sample.css is out of date but why is it only out of date when I add in html to my muse site?
    HELP!!!! I've searched other threads and to no avail I'm publishing so no direct ftp going on. the only thing I changed in business catalyst was the module stylesheet in order to style the blog. I've tried uploading and replacing all files nothing seems to work. the site is here:
    http://www.musicstudentsforhire.co.uk/musicians-samples.html
    It's only this page as it has the blog on. Also I've noticed when I've re-published occasionally it will show the mobile version on my desktop and not the desktop version??? no idea why that's happening so I've had to turn that off. any explanation on why that is happening would also be much appreciated.

    I haven't received an answer as of yet, I'll post t on here when I do. I de-activated the mobile site because it's my clients site so he needs it to be operational during the day. I hope someone gives me an answer soon.

Maybe you are looking for

  • Jsp:usebean How to get value of an object from a bean

    I am new to JSP and am struggling from past few days to solve a problem. Consider the below scenario Class Book{ private String author; public void setAuthor(String author) public String getAuthor(){ return author; } Class Rack{ private Book []books;

  • ITunes Crashes When Launched by Front Row

    Hey everyone, If iTunes isn't running when I launch Front Row, I have some issues when I try to play its music through the Front Row interface. I can select "Music" just fine from the four-icon menu, but as soon as I try "Playlists" or "Artists" or a

  • Switching tabs in a tabstrip

    I have a tabstrip with two tabs. Under the first tab i am displaying a table. The user has the option of selecting one or more rows of this table, and hit an "Edit" button. At this time, the selected rows will be picked and transferred to a second ta

  • RAID 5 Disk State Roaming - What to do?

    I have an Apple RAID card that has been giving me some fits lately. My current problem is in my RAID 5 set. I have all 4 drive bays in use. All 4 bays have green circles, so the disks seem to be fine, but the drive in bay 4 says its in "Roaming" as i

  • Creating a application dynamically for a component

    Hi, Does any one know how to create an application dynamically for a component, so without using SE80? I already found class cl_wdy_md_application, but I do not know if this is the right direction. Maybe somebode already solved this issue. Regards, R