Text file within jar file

Can anybody tell me if it's possible to read and write to a text file stored within the .jar file package? I can maintain a constant file length if that enables me to read and write.
cheers,
Steve

reading a text from, from a jar file..... if the jar is in your classpath you can call
getClass().getResourceAsStream ( "/myServerConfig.properties" );Note the "/", which stops the file from being interpreted as a class name, see Class.getResourceAsStream()
writing... nothing as easy as the reading solution above.
You'd probably have to actually "update" the JAR file contents with a new version of the text file.
regards,
Owen

Similar Messages

  • Static method to read text file within JAR.

    I've a small problem. I've got my JAR file stuff working great, so I thought I'd give a go to running it via WebStart. Through a little research, I've found that if you're distributing your application via WebStart, you need to pack up everything in a JAR file. This is no problem for the JDBC drivers, because its already in a JAR, so I should be able to distribute that fine.
    I've managed to digitally sign my application JAR and have a preliminary (i.e. untested) JNLP file set up.
    My problem is, my application gets its available data sources from an external text file. I've already written my own file I/O class which I use in my "commonfiles" package to read in a text file and return it as an array with each element holding a line from the text file. This class is basically just a bunch of static methods.
    So instead of rewriting this, I thought I'd just add a boolean flag to this method to state whether to load this file from the external file system or the JAR file. I've found out that to load a text file from within the JAR you have to use something like: -
    String str = (this.getClass().getResource("/myData.txt")).getFile();
    java.io.File fil = new java.io.File(str);
    java.io.FileReader fr = new java.io.FileReader (fil);
    java.io.BufferedReader bin = new java.io.BufferedReader (fr) ;The sticking point is that my method (ReturnFileAsArray()) is declared as static, because my own FileIO class is just a bunch of static methods to do file I/O stuff. Therefore, I can't use the above method because of the instance variable "this" (I assume).
    Is there any way I can load an included text file as above without having to declare my method as an instance method? I guess I could write a seperate class to do this for my commonfiles package, but I'd rather not if possible.
    Any ideas?

    Don't put a "flag" and code different ways to read files depending on whether it's in a JAR or not. Just use
    the getResource/getResourceAsStream API regardless. Hmmm.....so that will load it from either place depending on the situation? I keep getting a NullPointerException doing that, on this line: -
    String strFileName = (FileIO.class.getResource(fileName)).getFile();...although I've only tried it using the external local filesystem file (in the same directory) as I've not really finished setting up my WebStart stuff yet.
    Here is the method in question...
    public static String[] ReadFileAsArray(String dirName, String fileName, boolean bFromJAR) {
            String[] resultStringArray = null;
            StringBuffer strBuffer = null;
            StringTokenizer strTokenizer = null;
            FileReader fReader = null;
            BufferedReader bReader = null;
            int iElementCount = 0;
            if ((dirName.length() < 1) || (fileName.length() < 1)) {
                // Null parameters found. Failure.
                return null;
            } else {
                // Parameters correct, continue.
                try {
                    // Read the file contents and convert to String array.
                    //if (bFromJAR) {
                        // Open file from within JAR file.
                        String strFileName = (FileIO.class.getResource(fileName)).getFile();
                        File jarFile = new File(strFileName);
                        fReader = new FileReader(jarFile);
                    //} else {
                        // Open from local filesystem.
                    //    fReader = new FileReader(dirName + File.separator + fileName);
                    bReader = new BufferedReader(fReader);
                    strBuffer = new StringBuffer();
                    while (bReader.ready()) {
                        strBuffer.append(bReader.readLine() + "%%");
                    strTokenizer = new StringTokenizer(strBuffer.toString(), "%%");
                    resultStringArray = new String[strTokenizer.countTokens()];
                    while ((strTokenizer.hasMoreTokens()) && (iElementCount < resultStringArray.length)) {
                        resultStringArray[iElementCount++] = strTokenizer.nextToken();
                    bReader.close();
                    return resultStringArray;
                } catch (IOException e) {
                    return null;
        }I'm calling it using: -
    // Load the external file into a String array, one row for each element.
    String[] fileArray = FileIO.ReadFileAsArray(System.getProperty("user.dir"), "datasources.dat", true);Cheers on any info on this.

  • Getting error FF with my extension: cant find the file at jar:file in omni.jar!/chrome/browser/content/browser/ some junk text

    After installing my plugins to ff4 and ff5 I am getting error File not found.
    Firefox can't find the file at jar:file:///Applications/Firefox.app/Contents/MacOS/omni.jar!/chrome/browser/content/browser/%E6%A5%A6%E6%95%AC%E2%BC%BA%E2%BC%AF%E7%8D%95%E7%89%A5%E2%BD%B3%E6%B5%A1%E6%B1%AF%E4%B0%AF%E6%89%A9%E6%85%B2%E7%A5%B2%E4%84%AF%E7%81%B0%E6%A5%AC%E6%85%A3%E6%A5%B4%E6%B9%AF%E3%88%A5%E5%8C%B0%E7%81%B5%E6%BD%B0%E7%91%B2%E4%84%AF%E6%BD%A4%E6%95%A2%E4%8C%AF%E6%B9%AF%E7%89%B4%E6%89%A9%E7%91%B5%E2%95%A5%E3%80%B2%E5%8D%83%E2%B8%B5%E2%BC%B1%E6%BD%83%E6%99%AE%E6%9D%A9%E7%89%B5%E7%91%A1%E6%BD%A9%E2%BD%AE%E4%89%89%E5%91%85%E6%B5%A5%E2%BD%B0%E6%BD%83%E7%91%AE%E6%A5%B2%E7%95%A2%E6%95%B4%E3%84%B6%E3%9C%B8%E3%90%B4%E2%B8%B3%E6%89%A9e%E3%90%B4%E2%B8%B3%E6%89%A9e%08%01%EC%92%B0%E0%B0%BE%EC%92%B8%E0%B0%BE%EC%92%BC%E0%B0%BE%EF%BF%BF%EC%93%80%E0%B0%BE.

    Try:
    "Reset all user preferences to Firefox defaults" on the [[Safe mode]] start window.
    * http://kb.mozillazine.org/Resetting_preferences
    Delete the files extensions.* (extensions.sqlite, extensions.rdf, extensions.cache, extensions.ini) and compatibility.ini in the Firefox [[Profiles|profile folder]] to reset the extensions registry.<br />
    New files will be created when required.
    See "Corrupt extension files":
    * http://kb.mozillazine.org/Unable_to_install_themes_or_extensions
    If you see disabled, not compatible, extensions in "Tools > Add-ons > Extensions" then click the Tools button at the left side of the Search Bar (or click the "Find Updates" button in older Firefox versions) to do a compatibility check or see if there is an update.
    Create a new profile as a test to check if your current profile is causing the problems.
    See:
    * [https://support.mozilla.com/kb/Basic+Troubleshooting#w_8-make-a-new-profile Basic Troubleshooting: Make a new profile]
    If that new profile works then you can transfer some files from the old profile to that new profile (be careful not to copy corrupted files)
    See:
    * http://kb.mozillazine.org/Transferring_data_to_a_new_profile_-_Firefox

  • Trying to access the java script files via jar file in WEB SERVER

    hi all,
    I am trying to access the java script files via jar file ,which is present in Apache webserver in order to minimise the number of hits to app server.some thing like cache ...
    in jsp the code goes like this...
         <script type="text/javascript"  archive="http://localhost:14000/dojo.jar!" src="dojo.jar/parser.js" " ></script>{code}
    But i am not able to access the js file which is put in jar file present in the  webserver.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi,
    You can use DWR (Direct Web remoting) for that. It is easy AJAX for java. ou can directly call the java script function from java class and also java class from javaScripts..
    Regards,
    Hardik

  • How to list files from .jar file in applet?

    I have created applet and export all files to .jar file.
    I use File.list() method in applet to list files from one directory and that works ok but if I try to do that from web browser it sends exception AccessDenied meaning that File.list() isn't allowed in browser.
    I know what's the problem but I don't know how to solve it.
    What I want is to read from directory list of files.
    Help anyone?

    I will post here my code so that can be seen what I want to do:
    import java.awt.BorderLayout;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URLClassLoader;
    import java.nio.charset.Charset;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    public class test extends JApplet {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JTextPane jTextPane = null;
          * This is the xxx default constructor
         public test() {
              super();
          * This method initializes this
          * @return void
         public void init() {
              this.setSize(449, 317);
              this.setContentPane(getJContentPane());
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getJTextPane(), BorderLayout.CENTER);
              return jContentPane;
          * This method initializes jTextPane     
          * @return javax.swing.JTextPane     
         private JTextPane getJTextPane() {
              if (jTextPane == null) {
                   jTextPane = new JTextPane();
              return jTextPane;
         public void start(){
              File fileDir= new File("somedirectory");
              String strFiles[]= fileDir.list();
              String a="";
              for(int i =0;i<strFiles.length;i++){
                   a=a+strFiles;
              this.jTextPane.setText(a);
    Method init() is irelevant, it just adds JTextPane in applet.
    Method start() is relevant, it runs normaly when started from Eclipse but from browser it sends exception AccessDenied.

  • When I add a watermark and flatten the transparency, it duplicates the file within the file.

    When I add a watermark and flatten the transparency, it duplicates the file within the file.  (a 105 pg file becomes 210pgs)

    After doing so, use the Save As command to save the file under a new name.
    This should optimize it and reduce the file's size, sometimes dramatically.

  • How to get the class file of jar file

    hello all,
    is there any way to get the class file of jar file,as we have when we compile a java file we get class file
    same do we have any option to get the class file of jar file

    A jar file is a zip archive, so you can uznip it or extract the contents with the command "jar" - if it is what you need.

  • Since downloading firefoz 4, everytime I make a browser search I get a second page with :"Firefox can't find the file at jar:file://how can I solve the problem. Kindly reply to :ramses1@videotron.ca

    Question
    firefox 4, when I make a browser search I get a second page:"Firefox can't find the file at jar:file:///D:/Program Files/Mozilla Firefox/omni.jar!/chrome/browser/content/browser/<url></url>", how can I solve the problem.

    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 > Appearance/Themes).
    * Don't make any changes on the Safe mode start window.
    See:
    * [[Troubleshooting extensions and themes]]

  • I upgraded to Firefox 8. Now my home page says this: "Firefox can't find the file at jar:file:///C:/Program Files (x86)/Mozilla Firefox/omni.jar!/browserconfig.properties.

    This is what it says on my screen when I open Firefox:
    Firefox can't find the file at jar:file:///C:/Program Files (x86)/Mozilla Firefox/omni.jar!/browserconfig.properties.

    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes

  • When searching, I get this message: Firefox can't find the file at jar:file:///C:/Program Files (x86)/Mozilla Firefox/omni.jar!/chrome/en-US/locale/browser-region/region.propertiesproblems.

    when I enter a word in the search window (the one with the curved arrow at the end), I get this message:
    Firefox can't find the file at jar:file:///C:/Program Files (x86)/Mozilla Firefox/omni.jar!/chrome/en-US/locale/browser-region/region.propertiesproblems.

    Try the Firefox SafeMode to see how it works there. <br />
    ''A troubleshooting mode, which disables most Add-ons.'' <br />
    ''(If you're not using it, switch to the Default Theme.)''
    * You can open the Firefox 4/5/6/7 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 />
    ''Don't select anything right now, just use "Continue in SafeMode."''
    ''To exit the Firefox Safe Mode, just close Firefox and wait a few seconds before using the Firefox shortcut (without the Shft key) to open it again.''
    If it is good in the Firefox SafeMode, your problem is probably caused by an extension, and you need to figure out which one. <br />
    http://support.mozilla.com/en-US/kb/troubleshooting+extensions+and+themes

  • How to run .class file and .jar file in jdev9i

    I want to run .class file and .jar file in jdev9i,what should I do?
    Also,I want to generate .class file and .jar file in jdev9i,what should i do?

    Add the .class file containing the public static void main(...) method to the project by clicking on the + toolbar button in the navigator, open the project properties and properly set the additional classpath then right click on the .class in the navigator and say run. It should work, I've just tried it.
    Doesn't work for a .jar yet, in JDeveloper 9.0.3 it works both for .class and .jar
    Michel

  • How to use database file within jar archive

    Hi. I'm quite new in Java programming, and I'm wondering if what I did makes sense or not.
    In my applet I'm using a MS Access Database file, which is contained in the same Jar Archive like the Applet class file. I tried and tried to use this Database file directly but it wouldn't work. Than I read in some other forum that it is not possible to use the database file directly within the archive. First question: Is that true?
    Than I desided to extract the DB file in the init() method of my applet to the default temporary foulder. When the program is closed I use the destroy() method to delete it again. Everything works well now. But is this the typical way this is done?
    Thanks for help!

    Hi,
    here is the code which extracts the database file out of the jar archive (the same archive in which the class file is):
    //get the user temporary folder
    File TempFolder = new File(System.getProperty("java.io.tmpdir"));
    //create (empty) db file
    efile = new File(TempFolder, "steelSections.mdb");
    // if database file is not yet extracted
    if (!efile.exists()) {
    //get an input stream for the database file
    InputStream in = new BufferedInputStream(this.getClass().getClassLoader().getResourceAsStream(
    "FaST/db/steelSections.mdb"));
    //create an output stream for the db file on the file system
    OutputStream out = new BufferedOutputStream(new FileOutputStream(efile));
    //-Buffer to copy the data
    byte[] buffer = new byte[2048]; //buffer to copy the binary
    for (;;) {
    int nBytes = in.read(buffer); //read data
    if (nBytes <= 0)
    break; //no more data to read
    out.write(buffer, 0, nBytes); //write data
    out.flush(); //close out and in streams
    out.close();
    in.close();
    If you have the db file in an other jar archive file you need a referenze to the entry in the other jar archive. I'm not sure how to get this, but I'm sure you fill find a solution by searching in this forum...
    Good luck!

  • Accessing Video File within .Jar

    Ok, I am creating a project where I am using JMF to display several pre-created videos. The finished project is going to be placed on a cd and submitted in a contest. Because of this, I am compiling the finished project into an executable .jar file. From my previous experiences, I have found that accessing files inside a jar is much more complex than accessing just any old file. The only way I have found to successfully access files inside a jar is through InputStreams (opposed to URLs). This is where my issues begin.
    I have been searching throughout the internet for the past 2 days trying to find any way to create a Player using a type of InputStream. This doesnt seem to be possible the way it is set up. My obsticle here seems to be getting the Manager to realize the File. Here is what I've tried and the errors I got:
    File -- NoPlayerException -- Expected. When creating a file, it doesnt know to look inside the jar for the file, but to the location of the jar instead. Perhaps there is a way to tell URL to look for the file inside the jar. If so, please tell me how.
    File movie = new File("video1.mpeg");
    JOptionPane.showMessageDialog(null, "File: " + movie + "\n URL: " + movie.toURL() + "\n URI: " + movie.toURI() + "\n URL Parsed URI: " + movie.toURI().toURL(), "Error", JOptionPane.ERROR_MESSAGE); //JOptionPane used to display background information while program is running after compiled in .jar
    MediaPanel mediaPanel = new MediaPanel(movie.getURL());
    InputStream -- Compiling Error -- So my primary method of getting Files inside jars are out the window since there is no way to get the URL of InputStreams.
    InputStream movie = getClass().getResourceAsStream("video1.mpeg");
    MediaPanel mediaPanel = new MediaPanel(movie);
    Creating MediaLocator to file location -- java.net.MalformedURLException: no protocol: video1.mpeg -- I assume that basically means I'm screwed.
    MediaLocator movie = new MediaLocator("video1.mpeg");
    JOptionPane.showMessageDialog(null, "File: " + movie + "\n URL: " + movie.getURL(), "Error", JOptionPane.ERROR_MESSAGE);
    MediaPanel mediaPanel = new MediaPanel(movie.getURL());
    Using URL to get into .jar -- NoPlayerException -- No clue about this one. Just tried this a minute ago.
    URL movie = HannibalProject.class.getResource("video1.mpeg");
    JOptionPane.showMessageDialog(null, "URL: " + movie, "Error", JOptionPane.ERROR_MESSAGE); // Displays "URL: jar:file:/G:/Latin/HannibalProject.jar!/video1.mpeg" I do not know if this is correct or not, perhaps someone could tell me.
    MediaPanel mediaPanel = new MediaPanel(movie);If anyone can help me with this, I will be GREATLY appreciative. If anyone needs more information, additional code snippets, ect. please ask and I'll provide what is needed to help me.
    Edited by: Aussiemcgr on Jan 10, 2010 7:03 PM

    And there arises the pain-in-the-ass that is not yet clear to me. For this particular thing, it needs to be an application, not an applet. Which means I have to make it an executable (alternative might be a .bat, havent played with those for anything other than scripts) instead of something embedded. For whatever reasons, this is the efficiency of the school system or whatever the hell it is.
    The simple fact in all of this is that I have no information about the computer this is going to be ran on. Effectively, I am doing this all in the dark right now because I have been given NO guarantee that the computer(s) I attempt to run this on will even have the Java Virtual Environment on it. And, unfortunately, I have no way of finding any of this out because the Computer Program category of these things are not yet been taken seriously so preparation for judging is a last-minute thing.
    Basically, I am wanting to do this with the least amount of possibilities for Murphy's Law (which means I probably shouldnt be using JMF to begin with, but I hate that incomplete feeling) to happen. For the dark abyss I am traveling into, I'm wanting to leave as little external dependencies as possible. For applets, I have to assume that the computer has some sort of browser (sounds stupid, but it is the school system). Not to mention I've designed it from the ground up to work as an application, instead of an applet (roughly 20 hours of work so far, including text research and coding).
    The contest is Jan 30 so the date is approaching real quick. Quite honestly, the more I am looking at it, the more I am starting to consider getting rid of the videos altogether since I am pretty much done with the project with the exception of that. I would have 9 videos total (made only 1 to make sure it would work before making the other 8). The videos itself would only add an additional flair at best, and pretty much guarantee the 1st place for me. My teacher thinks my program's current capabilities, with just a mouse hover and mouse clicking interface with some animated gifs that allows access to several neatly displayed texts, would probably win me first place. However I feel I would go crazy if I actually had legitimate competition for once and lost because I didnt include this damn multimedia. Not to mention I want to include this on my portfolio in the somewhat distant future (along with my Poker Program I finished last month)...I dont know where I'm going with this...

  • Text Files in .Jar file

    Alright, I have my program packaged up in a .jar file. I have figured out how to access images that are in the .jar
    ImageIcon nextImage=new ImageIcon(Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("next.png"))); That works well.
    Now, When the program loads, I would like it to load some initial values from a .txt file that is in the .jar. How do i do that? Is this a situation where I have to use an inputStream? If so.... I need an example. I'm relativly new and I am learning as I go.
    I was previously loading these values using a BufferedReader and a FileReader, but that was before I decided i wanted all the files in the Jar.
    Txt file name: fields.txt
    jar. Taxi.jar
    Thanks a ton in advance.

    Yes, most likely you need an InputStream. Here's how to use the Java API documentation to help find a solution.
    You already know how to read a file containing an image by using ClassLoader.getSystemResource(). So, look at the API documentation for getSystemResource(). What does it return? It returns a URL. Ok, now what methods are available in the URL class that might help read a text file? Search the documentation for URL to find your answer.

  • File within jar

    I created a jar file for my application using eclipse
    within my project i have some file my application uses as images
    i have a issue with the path to write to access those files
    currently although all those files are already in the jar i have to create a folder duplicate those files and copy the jar in that folder to be able to use my resources.
    to be more specific assuming i have
    Package1
    Package1.class1
    Package2
    Package2.image
    what will be the path to write in class1 to open the image file?
    I print out the directory while the program is running and it is the directory in which the jar file is
    so i use this path
    ./myproject.jar/package2/images
    in class1 code but it can not find the file(no such file error)
    My question is what is the path to write in class1 to open a file located in package 2
    Thanks

    The relative path to an image file or other resource file is always in relation to the current class file that is executing.
    So your class in Package1 cannot have access to an image in Package2.
    It is just impossible.
    The only way to do this is to move your image files at a location relative to the class that requires the files within Package1.

Maybe you are looking for

  • How to import a transport from one SAP system to another SAP System?

    We have a requirement where the same security report needs to be made avialble across the whole SAP landscape - comprising of ECC6, PI7, BW, HR , SRM, CRM etc. To reduce the time and effort, is it possible to create the report in ECC6 attach it to a

  • [svn:fx-trunk] 13127: SystemManager was supposed to call ChildManager to finish initializing the top level window .

    Revision: 13127 Revision: 13127 Author:   [email protected] Date:     2009-12-21 13:42:09 -0800 (Mon, 21 Dec 2009) Log Message: SystemManager was supposed to call ChildManager to finish initializing the top level window.  LoaderConfig was not getting

  • Unable to Install 5.1.1 Update

    iPad 2 renders, "An error occured installing iOS 5.1.1." It is fully charged.  I have tried using the charger when updating.  I have also tried wiping it, but it still fails with the same error. In Diagnostics and Usage, the log shows, "Closest marke

  • Forms 11gR1 with Database Package

    Hi everyone, I'm asking this here, i need to know what i'm doing wrong. I have a database package that contains pipiled record. I want to use it in a form with forms builder. if i do select * from table(mypackage.myfunction()); in PL/SQL Developper,

  • Labels and Ratings Unavailable in Bridge

    I'm able to apply neither labels nor ratings to pictures in Bridge.  Additionally, although the Labels and Filters are offered under Select Filter Categories, neither actually appears in the Filter list.   Seems to affect CS5 now as well.