How to read some files inside the jar

Hi,
I have an applet that runs with JWS. The user can input some information and then I need to show this information in a web page. As the application can be run offline, I cannnot use JSP�s to generate the web page. The information is saved in a xml file, so I use a xsl parser to generate the html code. The problem is that I have to include some javascript files (.js). I put these files inside the jar, but, how can I read these files, or how can I reference these files from inside the html page ?
Thanks !

You can use getClass().getResource(classpath)
to get a stream version of the data from your
jar file. If you need to put it in a file, you
can write that stream to a file in a temp directory.
classpath is the classpath of your js file

Similar Messages

  • How to read, write file inside the JAR file?

    Hi all,
    I want to read the file inside the jar file, use following method:
    File file = new File("filename");
    It works if not in JAR file, but it doesn't work if it's in a JAR file.
    I found someone had the same problem, but no reply.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=180618
    Can you help me ? I have tried this for all night !
    Thanks in advance
    Leo

    If you want to read a file from the JAR file that the
    application is packaged in (rather than a separate
    external JAR file) you do it like this ...
    InputStream is =
    ClassLoader.getSystemResourceAsStream("filename");Better to use
    this.getClass().getClassLoader().getResourceAsStream();
    From a class near to where the data is. This deals with multiple classloaders properly.

  • How to read a file inside the JAR file

    Hi All,
    I want to save some preferences in a file called "preferences". I kept the preferences file under my java package.
    If i am running the code inside the NetBeans 6.9 IDE it's working file. But once i have created a JAR and try to run the application, it couldn't find the path.
    Please help me that how to resolve this issue. I don't want to save this preferences file outside of my JAR (i.e) within my java package.
    Here is the code,
    package mypackage;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    public class ReadFile
        private void writeFile()
            try
                OutputStream out = new FileOutputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                PrintWriter writer = new PrintWriter(out);
                writer.println("Hello Java!");
                writer.close();
                out.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        private void readFile()
            try
                FileInputStream fi = new FileInputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                BufferedReader br = new BufferedReader(new InputStreamReader(fi));
                System.out.println(br.readLine().trim());
                br.close();
                fi.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        public static void main(String[] args)
            ReadFile read = new ReadFile();
            read.writeFile();
            read.readFile();
    }If i run the JAR, i get the following error message,
    {color:#ff0000}*file:\my jar path\jarname.jar!\mypackage\preferences (The filename, directoryname, or volume label syntax is incorrect)*{color}

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • How to read a file inside a jar

    Hi All,
    I have a jar file which consists of several XML. I need to read one of the xml.
    If the XML are in a folder it is easy to read them by directly referencing them (e.g.:- "D/Test/Sample.xml";). But if these xmls are put in a jar file i am facing trouble in reading them.
    Can anyone please suggest how to read such files. Also if the classes and jar are not in the same directory.
    Any help in this regard will be highly appreciated.
    Thanks,
    Piyush

    nikhil_vinay wrote:
    yes i have already used "Class.getResourceAsStream ()". I guess it comes useful only when the class files and jar are in the same directory.No, wrong. The JVM has little or no concept of 'directories'
    and instead relies on the classpath of the application to find
    resources.
    Due to some problem my jar files and my codes are in different directory. So add them to the apps' claspath and it will all be sweet. The original
    responders advice will work just fine if the resource is on the classpath.
    (Of course, that reply was assuming the resource was in a jar file.
    If not, you will probably be needing to offer the user a JFileChooser
    to access the file.)
    Edited by: AndrewThompson64 on Mar 11, 2008 1:22 PM

  • Java Files inside the jar file cannot be read or accessed through Eclpse

    The Java File inside the jar file of the eclipse cannot be accessed through the Eclipse . It shows error for the modules in the jar file .
    But when compiled with adding the jar files to the class path the compilation is successful .
    How can i browse through the files in the jar like going into the function definition .
    TIA ,
    Imran

    Open MPlayer OSX and show the playlist (command-shift-p) then drag the file into the playlist. Click the file in the playlist and click the "i"nfo button. What does it list for file, video and audio format?
    Not all of the codecs used in avi and wmv files are available for OS X so I'm guessing your file happens to be using one that isn't...

  • How to Read all files inside resource Folder inside Jar?

    I have a Jar file,,,, The program reads for resource files in the resource folder inside the Jar. I want my program to read all files inside this folder without knowing the names or the number of files in the folder.
    I am using this to make an Applet easy to be updated with spicific files. I just want to add a file inside the resource folder and Jar the program and automatically the program reads what ever is in there!!
    I used the File class to get all file names inside the resource folder. it works fine before Jarring the program. After I jar I recieve a URI not Herarichy Exception!!
    File fold=new java.io.File(getClass().getResource(folder).toURI());
    String[] files=fold.list();
    I hope the question is clear!!

    How to get the directory and jar file that you class resides in:
    // returns path and jarfile (ex: /home/mydir/my.jar)
    public String getJarfileName()
            // Get the location of the jar file and the jar file name
            java.net.URL outputURL = YourClass.class.getProtectionDomain().getCodeSource().getLocation();
            String outputString = outputURL.toString();
            String[] parseString;
            int index1 = outputString.indexOf(":");
            int index2 = outputString.lastIndexOf(":");
            if (index1!=index2) // Windows/DOS uses C: naming convention
               parseString = outputString.split("file:/");
            else
               parseString = outputString.split("file:");
            String jarFilename = parseString[1];
           return jarFilename;
    }If your my.jar was in /home/mydir, it will store "/home/mydir/my.jar" in jarFilename.
    note: getLocation returns "file:/C:/home/mydir/my.jar" for Windows/DOS and "file:/home/mydir/my.jar" for windows, thus why I look for the first and last index of the colon so I can correctly split the string.
    If you want to grab a file in the jar file and get an InputStream, do the following:
    import java.io.*;
    import java.util.Enumeration;
    // jar stuff
    import java.util.jar.*;
    import java.util.zip.ZipEntry;
    public class Jaris
       private JarFile jf;
       public Jaris(String jarFilename) throws Exception
           try
                           jf = new JarFile(jarFilename);
           catch (Exception e)
                jf=null;
                throw(e);
       public InputStream getInputStream(String matchString) throws Exception
           ZipEntry ze=null;
           try
              Enumeration resources = jf.entries();
              while ( resources.hasMoreElements() )
                 JarEntry je = (JarEntry) resources.nextElement();
                 // find a file that matches this string from anywhere in my jar file
                 if ( je.getName().matches(".*\\"+matchString) )
                    String filename=je.getName();
                    ze=jf.getEntry(filename);
          catch (Exception e)
             throw(e);
          InputStream is = jf.getInputStream(ze);
          return is;
       // for testing the Jaris methods
       public static void main(String[] args)
          try
               String jarFilename=getJarfileName();
               Jaris jis = new Jaris(jarFilename); // this is the string we got from the other method listed above
               InputStream is=jis.getInputStream("myfile.txt"); // can be used for xml, xsl, etc
          catch (Exception e)
             // this is just a test, so we'll ignore the exception
    }Happy coding! :)
    Doc

  • Updating an XML file inside the Jar executable

    Hello all!
    I would like to ask how can i update an XML file that is packaged inside my jar file?
    For intstance:
    I have a Java Application in NetBeans
    Inside a package i have constructed a custom .xml file.
    I can read from this file using
    .....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
    I want to update an entry in my xml file so the jar contains now the newly updated file.
    Thanks everyone who spends his time to read this. Hope someone can help me.

    Even if it were possible, it would be a bad idea. A jar file is something you deploy. It can be really hard to manage ongoing maintenance if the thing you deploy changes after you've deployed it.
    Just create a file, in an appropriate place given the user's OS, to hold data that changes after the jar has been deployed. Your application will still be in a single jar; it's just that the application will happen to create additional content outside the jar.

  • Reading a file in the JAR

    i have a jar with class files and xml files in it. my application uses this jar and a particular class has a link to the xml. but while compiling, it shows path not found. the application couldnt read the xml file in the jar. how to set the path or read the xml file
    XML file in JAR:
    SQLMaps/admin/sample.xml [folder structure inside the jar file]
    my application has a path like SQLMaps/admin/sample.xml
    but how do we point to the xml file in the jar
    Regards
    Pradheep

    thanks anyway
    but i need the application to read the xml file in the jar file
    to be more clear.
    the jar file has xml in a specified folder.

  • How to read a file outside my .jar

    Hello!
    I have my j2me application in a .jar file , and my application needs to read a .txt file which is outside my .jar but in the same directory.
    I tried to do :
    InputStream input = getClass().getResourceAsStream("/myfile.txt");
    as well as
    InputStream input = getClass().getResourceAsStream("myfile.txt");
    but nothing is working...
    Could you help me, please??? I'm getting crazy with this :(
    Thanks in advance!

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • How to display PDF file, inside the SWF file or flash exe file

    I  have create the application for Employee details using flash actionscript 3.0
    This application is to view the organization employee details, iam using the tree component in this application,
    the tree component is to get the dada via xml file, this xml file save in the remote server ,
    I display the PDF file inside the swf file to using " StageWebView" class . Then i goto Publish Setting to change the  player Adobe Air 2.6 and run the flash file using
    ctr-l + Enter . It is work correctly the PDF file is Displayed inside the Swf Output. But I Publish this file to exe . then i run the exe it is not working .
    The application is run The xml data is onely get and displayed the Tree component then i click the tree item employee name the xml data in not display and the pdf file is not open .
    Pls Help...................

    hi i need to display the pdf file inside the swf file or flash exe file .
    I use the navigateToURL class this is open the pdf file on the browser. I want to display the pdf file in the swf window .
    Please suggest.

  • How to preserve some files inside application directory after a Redeploy?

    Hi, all.
    My application (recently refactored to run from JServ to OC4J) have an Upload procedure that puts a file inside the context from wich the Upload.jsp is being called. I.e, www.xyz.com/app_name/upload.jsp when called puts a file inside $ORACLE_HOME\j2ee\OC4J_xxx\applications\blaff\uploaded_files (blaff is the directory that contains the Upload.jsp file).
    Now, we have about 30MB inside uploaded_files directory and a problem: when redeploying the application, the "blaff" directory is removed and all uploaded files are lost.
    There is a way to "preserve" these files? The other issue is related to big quantity of application images, pdf's and Xls's: about 40MB!!! My final EAR file is about 60MB, and it's difficult to transmit it from developer's machine to the server's machine through a VPN.
    Can somebody help me with this issue?
    Thanks!

    You can use getClass().getResource(classpath)
    to get a stream version of the data from your
    jar file. If you need to put it in a file, you
    can write that stream to a file in a temp directory.
    classpath is the classpath of your js file

  • Need signed applet to read a file in the jar?

    i have an applet and i need to read a file (just a picture .jpg) within the jar. but i got a security exception when i try to make the File object for this jpg
    thanks and sorry for my english

    Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResorce("FileName.jpg"));i need to make something like this
    File file = new File("picture.jpg");
    the idea is verify that picture.jpg is really the picture that i put and not other with the same name... and if it is a file objet i can see the last modification date, to make a validation...
    another way is to read some pixels and verify that its colors dont change... but i dont know how to do this neither.
    but thanks anyway!

  • How to read multiple files in the same folder?

    Suppose I have 100 txt files in the same folder, and I want to read them one by one. (order is not important). File name is also part of the information I want.
    How to do that?
    Thanks

    You need to use the directory to create a File (use the path name, w/o a file name). Then you need to ask for a list() (array of String containing name). To do that you'll need to implement the FilenameFilter interface, writing an accept() method that returns true if the file's name ends with ".txt".
    If that's not perfectly clear, try the java.io API docs and return more specific questions.

  • How to read from file just the 2nd line onwards?

    hi guys can anyone help me?
    how to read from the file if the file was like this
    2 2
    2 1
    1 3
    and i want to get the 2 1 ,just the 2nd line and the 3rd line?
    i tried using the string tokenizer but it kept saying
    no such element
    i tried this code:
    StringTokenizer cols = new StringTokenizer(s," ");
         temp =  (String) (cols.nextElement());
         num_rows = Integer.parseInt(temp);
         temp = (String) (cols.nextElement());
         num_cols = Integer.parseInt(temp);
         matrix = new int [num_rows][num_cols];
         // to add all the values in the data file into an array                         
         while ( s!= null ) {
         StringTokenizer st1 = new StringTokenizer (s);
               while (st1.hasMoreTokens()){
                     for (i=0; i<num_rows; i++){
                          for (j=0; j<num_cols; j++)
                             matrix[i][j] = Integer.parseInt
                                ( st1.nextToken());
                } // whilecan anyone please help me?
    thanks

    This will read the file witout the first line:
    import java.io.*;
    import java.util.*;
    public class Read2
    public static void main (String[] args)
         try
              FileReader     file = new FileReader("f.txt");
              BufferedReader buff = new BufferedReader(file);
              String         line  = buff.readLine();
              while (line != null)
                   line = buff.readLine();
                   System.out.println(line);
              buff.close();
         catch(IOException e)
              System.out.println("IO Error");
    }       Noah

  • How to read resource file under the WEB-INF through ClassPathResource

    I have an xml file under the directory WEB-INF but WEB-INF/classes, I want to read it through ClassPathResource class from Spring, and where I read this xml file is not in a Servlet class, how can I do? Thank you.

    Webmethods should be able to handle it. if not you should convert the tline content into one xstring and pass it to webmethods.
    othe option
    if you are on WAS6.20 and above you can use BSP to achieve what you are looking for.
    Regards
    Raja

Maybe you are looking for

  • How can I install a second version without affecting the first?

    How can I install a second version of FF without affecting my original installation?

  • How to make schema read only ?

    Hi, database=10.2.0.3 o/s=windows i want to make a schema read only when users connect to database they can view it update and insert must be restricted to all users how it can be done example There is XYZ schema in that I have around 200 roles assig

  • Re: Tecra A8 PTA83: WLan loses the connection

    For the third time I have attempted to load on SP3 for XP to my Tecra laptop. Every time, despite upgrading the driver for the wireless network intel chip to version 12, I loose all internet connection. Can someone please help me out here. I am sure

  • Splitting Input/out put tax to different profit centers

    My sales order has two products and two different profit centers assigned in the Material master. Product A             10000  ( PC x) Product B               5000   (PC Y) Output tax             2000 Custmer Dr,        17000/- I want to split  out p

  • Where are the Oracle Data Binding Frameworks for Oracle Objects?

    Oracle offers a few different options for data-binding frameworks to Oracle relational data. Amongst them they include TopLink and the Oracle Application Development Framework (ADF)in JDeveloper 10G. J2EE also offers the EJB standard framework. Both