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();
}

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.

  • 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

  • Urgent Help:read from text file and write to table

    Hi,
    I'm a super beginner looking for a vi to read this data from a text file and insert it into a table:
       #19
    Date: 05-01-2015
    ID= 12345678
    Sample_Rate= 01:00:00
    Total_Records= 2
    Unit: F
       1 03-23-2015 10:45:46   70.1   3.6
       2 03-23-2015 11:45:46   67.7   2.7
    Output table
    #     date                 time                 x          y        Sample rate    Total Records
    1          03-23-2015     10:45:46        76.8     2.8      01:00:00           2
    2          03-23-2015     10:45:46        48.7     2.1      01:00:00           2
    Thanks for your help in advance.
    Attachments:
    sample.txt ‏1 KB

    jcarmody wrote:
    Will there always be the same number of rows of noise header information?
    Show us how you've read the data and what you've tried to do to parse it.  Once you've got the last rows, you can loop over them using Spreadsheet String to Array (after cleaning up a few messy spaces).
    Jim,
    I didn't know you're that active on here.
    Yes, There will always be the same number of noise header information.
    I'll show you in person
    Regards,

  • 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

  • Need help reading a text file!!!!

    What i need is a simple example of how to read data
    from a text file into a applet
    so i can put the values in the file into a array
    the file will be in the same folder as the the applet
    say i have a file myfile.txt with the following values written in it
    5
    10
    15
    20
    i want to read them into a simple array myarray[]
    for later use
    everything ive tryed wont work and i havent gotten a response in the the new to java forum

    //set up file reader
    java.io.BufferedReader in = new java.io.BufferedReader( new java.io.FileReader("myfile.txt") );
    //set up vector as we dont know how many lines there are in file
    java.util.Vector vect = new java.util.Vector();
    //store lines in vector
    while(in.ready())
    vect.add( in.readLine().trim() );
    //close file
    in.close();

  • 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(); }

  • Read from Text File - Help Bug?

    Hi - I am currently working on LV8 and I think that there is some misunderstanding potential in the help file. To be more exact in the help to the "Read From Text File" VI.
    The description for "count":
    " ... If count is <0, the function reads the entire file. The
    default is –1, which indicates to read a single line if you placed a checkmark
    next to the Read Lines shortcut menu item and to read the
    entire file if you removed the checkmark next to the item. "
    If count is lower than zero, the function reads the entire file. That sounds clear to me.
    The default is -1, which indicates to read a single line if you placed a checkmark next to the "Read Lines" shortcut menu item. Now what? Does it read a single line or the whole file?
    .. and to read the entire file if you removed the checkmark next to the item. I thought it reads the whole file if I use -1 ?
    the VI itself behaves as I'd expect it to:
    * If I place a checkmark next to Read Lines and put -1, I get an array containing the lines
    * If I remove the checkmark, I get only a single string item.
    Now where is the error? Is the VI not working properly or only the description a little bit ... strange ?

    ?hein??
    ?what?
    Both you guys lost me..
    And I drink coffee without sugar (being sweet enough, already) 
    Here is what I get from Context Help on the Read From Text File:
    Read from Text File
    Reads a specified number of characters or lines from a byte stream file. By default, this function reads all characters from the text file. Wire an integer value to count to specify how many individual characters you want to read starting with the first character. Right-click the function and place a checkmark next to the Read Lines option in the shortcut menu to read individual lines from the text file. When you select the Read Lines option in the shortcut menu, wire an integer value to the count input to specify how many individual lines you want to read from the file starting with the first line. Enter a value of -1 in count to read all characters and lines from the text file.
    Humm.
    New feature (again)..  If you select checkmark the Read Lines option, it will not send the text to a sting indicator, as shown in the attached image.  If selected, then it's expecting to write lines to an array of strings...  WHY???  I don't know..  I'll ask..
    Strange...  LV8 is full of mysteries... 
    RayR
    Attachments:
    bad write file.JPG ‏33 KB
    more bad write file.JPG ‏12 KB

  • Read from Text File Detailed Help need Clean-up

    This is probably well known and nobody has bothered fixing it but the detailed Help of the "Read from Text File" function is sort of ambiguous:
    -  statement 1: refnum out is the refnum of the file that the function read. You can wire this output to another file function, depending on what you want to do with the file. The default is to close the file if it is referenced by a file path or selected from the file dialog box. If file is a refnum or if you wire refnum out to another function, LabVIEW assumes that the file is still in use until you close it.
    - statement 2: If you wire a path to file, the function opens the file before reading from it and closes it afterwards.
    I have found statement 1 to be correct, which makes statement 2 incomplete (and sort of tautological in the sense that 1) you expect LabVIEW to open the file before reading from it if you provide a path instead of a refnum... and 2) if you use a path input to file AND use the refnum out for some other function, the file is NOT closed, as correctly stated in statement 1).
    Just sayin' ...

    X,
    It deeply concerns me that you would take my response to mean indifference. I certainly had no intention to belittle what you had to say. On the contrary, I took this up with the concerned team, and had a small discussion. If you say that what someone says on this forum is of lesser or no value to National Instruments, you could not be more wrong. It defeats the whole purpose of this public forum.
    My point was not that it is not an issue, it certainly seems to be. Please be rest assured that even if it does not look like it from the outside, each comment however big or small is taken back to our workplaces and some thoughts poured over it. 
    On the whole, I recognise that I had a role to play in this misunderstanding of tone, and I sincerely apologise.
    Warm Regards,
    Prashanth N
    National Instruments

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

  • Why does Read from Text file default to array of 9 elements

    I am writing to a text file starting with a type def. cluster (control) of say 15 dbl numeric elements, that works fine I open the tab-delimited text file and all of the elements appear in the file.  However when I read from the same text file back to the same type def. cluster (indicator), the read from text file defaults to 9 elements?? Is there a way to control how many elements are read from the file.  This all works great when I initially use a cluster of 9 elements and read back to a cluster of 9 elements.
    Solved!
    Go to Solution.

    From the LabVIEW Help: http://zone.ni.com/reference/en-XX/help/371361G-01/glang/array_to_cluster/
    Converts a 1D array to a cluster of elements of the same type as the array elements. Right-click the function and select Cluster Size from the shortcut menu to set the number of elements in the cluster.
    The default is nine. The maximum cluster size for this function is 256.
    Aside: so, how many times has this question been asked over the years?

  • How to open saved files using 'read from text file' function

    Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
    Here are some screenshots on part of my program  
    let me know if you guys would need more information / screenshots thank you!
    Attachments:
    ss_save.jpg ‏94 KB
    ss_open.jpg ‏94 KB
    modified_writetotextfile.jpg ‏99 KB

    Ohmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
    ( ps . cant connect it now unless my program is working otherwise labview will crash ) 
    ( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
    The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
    Attachments:
    frequency detactor.vi ‏53 KB
    signal generator.vi ‏13 KB
    attachment.ashx.vi ‏40 KB

  • Read from text file vi won't read file...

    I am very new to LV programming so I hope you forgive any stupid mistakes I am making.   I am using Ver. 8.2 on an XP machine.
    I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device.   Currently I am just using two data sets, each in their own small text file.  The delimiter is two commas ",,".
    The program works fine as written when run in the regular programming environment.   I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file.   I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place.  Each small text file is identified and named with a 4 digit number "ID".   I built it twce, and get the same result.  I also built it into an installer and unfortunately the bug travelled into the installation as well.
    Here is the overall program code in question:
    Here is the reading and parsing subvi:
    If you have any idea at all what could cause this I would really appreciate it!
    Solved!
    Go to Solution.

    Hi Kiauma,
    Dennis beat me to it, but here goes my two cents:
    First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier.  By any chance, have you observed error 7 when you try to read your files and get an empty data set?  (You've probably seen that error before - it means the file wasn't found)
    If you're seeing that error, the issue probably has something to do with this:
    Relative paths differ in an executable.  This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes.  Also, because an installer contains the executable, building the installer will always yield the same results.
    Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
    I hope this is helpful...
    Jim

  • Read from text file and seperate column

    hello,
    I have a problem reading my text file. This text file is downloaded from weather link. All data will be changed upon the selection of user. my problem is I can read the data column by column but i cannot retrive the right column header for each data. I also attached the test file. Can somebody help me? Thanks in advance..
    Attachments:
    download.txt ‏8 KB
    read text file.JPG ‏11 KB
    read data.JPG ‏43 KB

    Hi
    Sorry, I missed that one. The file formatting is strange though. It uses spaces to separate columns but also within columns. I attached a modified VI that tries to take care of that, but it fails at the columns "Solar Energy" and "Hi Solar Rad.". This is very difficult to read programmatically as there's one space each between "Solar", "Hi", and "Solar" again. So how do we distinguish between column separator and space within column?
    Is download.txt the original file? Or was it probably modified by an editor that would replace tabs by space characters?
    Attachments:
    test-mod-2.vi ‏11 KB

Maybe you are looking for

  • Photoshop CS4 64bit suddenly stop working

    Having problems with Photoshop CS4 64bit version stop running for me giving me this error message  with these details: Problem signature:   Problem Event Name:    APPCRASH   Application Name:    Photoshop.exe   Application Version:    11.0.1.0   Appl

  • Context-Sensitive Help Issues

    I have problem where context-sensitive help markers disappear from my .h files. I started with a .h file from my old WebWorks project. After a little reformatting, I was able to get the CSH Map IDs to load and map properly to my RH topics (I had to d

  • I just upgraded to Version 8 & wnat to know how to add a link to Google Maps om the toolbar at the top of the home page.

    I just submitted a question.....opened an account...got an e-mail that said there was a response to my question, all I had to do was go to the link in the e-mail. The window where I thought the response closed. Where is the response to my question?

  • SDK for creating PDFs, that can be emailed to end user?

    Apologies if this is in the wrong section I have been searching for a while but haven't found anything yet that I can see that covers my question, so please redirect me if this is a common/easy question! This is not a matter of the user clicking on s

  • Macbook Pro 17 Anti-Glare LCD Problem

    Here is the LCD screen on my MBP on black background. The back light is more or less very uneven. Is this normal to other Macbook pro anti-glare users? [IMG]http://img145.imageshack.us/img145/2341/dsc0627.th.jpg[/IMG]