Read a text File inside a JAR

I want to create a plain text file and pack into a JAR file together with my Java Applet such that I can read something inside the flat file as a parameter for the Java Applet. Is that possible to do that? Any sample code?

Look at Class.getResourceAsStream()
It'll let you load non-Java resources from the Jar file.
Then, you'll have an input stream to read directly.
Probably something along the lines of
     // to load as text file
     // Note : assumes that myfile.txt is in root directory of jar file
     InputStream is = getClass().getResourceAsStream ("/myfile.txt");
     BufferedReader bufReader = new BufferedReader ( new InputStreamReader ( is );
     // to load as properties file
     InputStream is = getClass().getResourceAsStream ("/myfile.txt");
     Properties myProps = new Properties();
     myProps.load ( is );regards,
Owen

Similar Messages

  • How to read a text file from a Jar file

    Hi
    How can I read a text file from a Jar file?
    Thanx in advance..

    thanx
    helloWorld it works.damn, I didn't remove it fast enough. Even if it is urgent, it is best not to mention it, telling people just makes them take longer.

  • Help! Reading a text file in a JAR

    How do I read a text file in a jar? (NON-applet).
    Following doesn't work:
    File f = new File("res\\dictionaryuk.txt");
    Neither does this:
    InputStream in = this.getClass().getResourceAsStream("res\\dictionary.txt");
    (I read somewhere else here that one should use resources instead of files in a JAR, but I'm not certain about that, or why?)
    It's not the pathname because I've tried everything.
    "res\\dictionaryuk.txt"
    "res/dictionaryuk.txt"
    "\\res\\dictionaryuk.txt"
    "\\dictionaryuk.txt"
    "dictionaryuk.txt"
    ...you name it
    And yes, the text file IS in the JAR.
    Any suggestions? Sample code?

    Okay, here is a quick example of how to do it that I tested and works...
    I get the same values for the ZipEntry method and the InputStream.available method, but the available method is used for slightly different purposes, and may not always return the full size of the file (I have seen some instances where the value returned was always 0). Anyway, here it goes:
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.jar.JarFile;
    import java.util.zip.ZipEntry;
    public class JARFileReading
         public static void main(String[] args)
              String fileName = "res/TestApplet.html";
              InputStream is = JARFileReading.class.getResourceAsStream(fileName);
              try
                   System.out.println("Input Stream.avaliable: "+is.available());
                   if (is != null)
                        is.close();
              } catch (IOException e)
                   e.printStackTrace();
              File jarFile = new File("JarFile.jar");
              if (!jarFile.exists()) System.exit(0);
              JarFile theJar = null;
              try
                   theJar = new JarFile(jarFile);
                   ZipEntry theFile = theJar.getEntry(fileName);
                   System.out.println("Zip Entry.getSize: "+theFile.getSize());
                   System.out.println("Zip Entry.getCompressedSize: "+theFile.getCompressedSize());
                   is = theJar.getInputStream(theFile);
                   System.out.println("JarFile.getInputStream.available: "+is.available());
                   if (theJar != null)
                        theJar.close();
                   if (is != null)
                        is.close();
              } catch (IOException e1)
                   e1.printStackTrace();
    }

  • How do I read a text file in a Jar Executable?

    Hello All,
    I have a need to package a text file into a Jar Exectable file and then have my java code read that text file in using a BufferedReader. Can anyone out there tell me how to do this? My first question is how do I reference this file by the path name? O, I'm also using Windows.
    Thanks for your help.
    Karl

    I have the same problem with kportner . I did by joop_eggen but I got the error at:
    BufferedReader in = new InputStreamReader(is);Can't conver from BufferedReader to InputStreamReader
    When I up my applet to server and get it from client. My applet couldn't read the text file.
    Any one help me!
    Thanks.

  • Reading a text file in a jar

    I make an application that need to acces to a small text file within a jar file.
    Never used it before, and don't really know how to do it correctly.
    could anyone show me the way to create this small part of code ?
    Thanks.

    Just use the getResource or getResourceAsStream. They exist in the java.lang.Class class (which actually call the current ClassLoader which has the same methods).
    An example follows below, the text file should be added to the root of the jar file.
    Don't forget the first / in the filename, if you do the method will return null..
    ----- Code begin -----
    import java.io.*;
    public class Test
         public static void main(String args[]) throws Exception
              InputStream in = Test.class.getResourceAsStream("/test.txt");
              BufferedReader reader = new BufferedReader(new InputStreamReader(in));
              System.out.println(reader.readLine());
              reader.close();
    ----- Code end -----
    Good luck,
    Daniel

  • How can I read a text file inside the .xsjs?

    I need to read line by line of a text file just like FileReader and BufferedReader in Java. It contains a script SQL to insert data in my DB. Can I use some API?

    There is no API that allows you to access the file system of the server in XSJS. You would need to upload the file from the client side and it will appear as a array buffer in the request object.  From there you can convert the array buffer to a string and process however you like.
    For example:
      var content = "";
        content = $.request.body.asArrayBuffer();
        var array = new Uint8Array(content);
        var encodedString = String.fromCharCode.apply(null,array),
             decodedString = decodeURIComponent(escape(encodedString));
            content = decodedString;
        var lines = content.split(/\r\n|\n/);

  • How to make an applet to read the Text file present inside a jar

    Hi All,
    I have writen one applet named ReadFile.java which reads a text file present in the same directory and does some manipulation of text file contents.
    The applet code runs successfully when i run the applet in command prompt like
    {color:#ff0000}*java ReadFile*{color}
    And i am getting the needed results.
    Then i made a jar file with the applet code and text file as
    {color:#ff0000}*jar cvf rf.jar ReadFile.class File1.txt*{color}
    Then i have inlcuded this applet inside a html file as
    {color:#ff0000}*<applet code= "ReadFile.class" width= "500" height= "300" archive = "rf.jar" ></applet>*{color}
    after this when i load the html file, the applet code is not executed fully. Its throwing FileNotFoundException: File1.txt.
    Applet is not recognizing trhe text file present inside the jar file.
    Can any body explain me how to overcome this problem. Any setting needs to be done for making the applet indicate the presence of Text file inside the jar file.

    what code in your applet gets the text file and reads it? are you using getResource or something similar?

  • Reading a text file in archive in jar

    Hi,
    I am unable to read a text file in my jar archive.
    Example code:
    try
    InputConnection con =
    (InputConnection) Connector.open("file://text/info.txt", Connector.READ);
    InputStream in = con.openInputStream();
    StringBuffer buf = new StringBuffer();
    int ch;
    while((ch = in.read()) != -1 )
    buf.append((char) ch);
    in.close();
    form.append(buf.toString());
    } catch (Exception e) { e.printStackTrace(); }
    Any ideas how I can do that?
    Thanks.

    You have to use java.lang.Class`s getResourceAsStream method. Your code:
    try
    StringBuffer buf;
    Class mc = buf.getClass();
    InputStream in = mc.getResourceAsStream("/text/info.txt");
    buf = new StringBuffer();
    int ch;
    while((ch = in.read()) != -1 )
    buf.append((char) ch);
    in.close();
    form.append(buf.toString());
    } catch (Exception e) { e.printStackTrace(); }

  • Running a batch file inside a jar

    HI all
    I created a jar file , in which i need to run a batch file , so i wrote a main class to execute the run the batch file , but when iam running the jar it is searching for the given batch file out side the jar.
    my code is some thing like below
         public static void main(String args[])
              try
                   Runtime rt=Runtime.getRuntime();
                   Process process=rt.exec("%DIRNAME%/start.bat");
       InputStreamReader reader =
                      new InputStreamReader ( process.getInputStream () );
                   BufferedReader buf_reader =
                       new BufferedReader (  reader );
                    String line;
                    while ((line = buf_reader.readLine ()) != null)
                                 System.out.println (line);
              catch (IOException e) {
                    System.out.println (e);
         }so please help me.. is it the problem in specifing the path...?
    are does it have any other method to read the stream functions ..
    thanks in advance
    sam

    I don't think this will work. You could not go to a command line and enter, "%DIRNAME%/start.bat" if start.bat was inside a jar - the CLI doesn't know how to read a batch file inside a jar.
    I think it would work to programmatically read the lines of start.bat (when it is inside the jar) into an array of Strings and use Runtime.exec with the array as the argument.
    It would also work to extract the start.bat file, then execute it using Runtime.exec.

  • How to edit a text file inside jar

    Hi all;
    I have a code that created text file and put this file to other jar archive.
    How can I edit this text file inside jar, add string to this file ?
    Thanks,

    Unpack the jar, edit the file, repack the jar.

  • 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 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

  • 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.

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

Maybe you are looking for

  • New problem again, This operation could not completed as there's no video

    I don' t understand what is the problem, I work with FCP 6.0 and Quicktime 7.4.1 very well until today, when I tray to capture from DV devices ( note that the capture window says PREVIEW DISABLED , but I can remote the camera, mark tc in , out FFW RE

  • Web Gallery Template Font Size Adjustment

    When I am in the Web module and using one of the templates (Flash or HTML), I would like to be able to adjust the font size of all the text used for the titles, headings, captions, etc. In general, I find the default font sizes too small, especially

  • Not Updating in Central SLD

    Hello, Upon performing our daily system checks, one of the item is to monitor the sending of SLD data of the installed systems in the System Landscape to the Central SLD which in our case is the XI box. Four of our systems having Java stack did not u

  • LOV is Extracting By It-self in 3-tier

    Could anyone can tell the reason forthis :- I have written some code for calling the LOV in different-2 conditions For that I had written the below code -      if :blk_detail1.nu_serial_no = 1 then           if :blk_head.ch_reference_type = 'O' then

  • Departments in a new page _ FR Report

    Hi All, We have got 100 departments in the Cube. We need to generate a report where each department will come in a new page. In rows we have account(Suppress missing),we have only ne column budget...........we need to generate a report with budget of