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

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.

  • 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

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

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

  • Open and read from text file into a text box for Windows Store

    I wish to open and read from a text file into a text box in C# for the Windows Store using VS Express 2012 for Windows 8.
    Can anyone point me to sample code and tutorials specifically for Windows Store using C#.
    Is it possible to add a Text file in Windows Store. This option only seems to be available in Visual C#.
    Thanks
    Wendel

    This is a simple sample for Read/Load Text file from IsolateStorage and Read file from InstalledLocation (this folder only can be read)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using System.IO;
    namespace TextFileDemo
    public class TextFileHelper
    async public static Task<bool> SaveTextFileToIsolateStorageAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    async public static Task<string> LoadTextFileFormIsolateStorageAsync(string filename)
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    async public static Task<string> LoadTextFileFormInstalledLocationAsync(string filename)
    StorageFolder local = Windows.ApplicationModel.Package.Current.InstalledLocation;
    string returnvalue = string.Empty;
    try
    var file = await local.OpenStreamForReadAsync(filename);
    using (StreamReader streamReader = new StreamReader(file))
    returnvalue = streamReader.ReadToEnd();
    catch (Exception ex)
    // do somthing when exception
    return returnvalue;
    show how to use it as below
    async private void Button_Click(object sender, RoutedEventArgs e)
    string txt =await TextFileHelper.LoadTextFileFormInstalledLocationAsync("TextFile1.txt");
    Debug.WriteLine(txt);
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

  • 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

  • LabVIEW for ARM 2009 Read from text file bug

    Hello,
    If you use the read from text file vi for reading text files from a sdcard there is a bug when you select the option "read lines"
    you cannot select how many lines you want to read, it always reads the whole file, which cause a memory fault if you read big files!
    I fixed this in the code (but the software doesn't recognize a EOF anymore..) in CCGByteStreamFileSupport.c
    at row 709 the memory is allocated but it tries to allocate to much (since u only want to read lines).
    looking at the codes it looks like it supposed to allocated 256 for a string:
    Boolean bReadEntireLine = (linemode && (cnt == 0)); 
    if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;    //BUFINCR=256
    but cnt is never false since if you select read lines this is the size of the file!
    the variable linemode is also the size of the file.. STRANGE!
    my solution:
    Boolean bReadEntireLine = (linemode && (cnt > 0));  // ==
     if(bReadEntireLine) {    //if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;
    and now the read line option does work, and reads one line until he sees CR or LF or if the count of 256 is done.
    maybe the code is good but the data link of the vi's to the variables may be not, (cnt and linemode are the size of the file!)
    count should be the number of lines, like chars in char mode.
    linemode should be 0 or 1.
    Hope someone can fix this in the new version!
    greets,
    Wouter
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

    I have another solution, the EOF works with this one.
    the cnt is the bytes that are not read yet, so the first time it tries to read (and allocate 4 MB).
    you only want to say that if it's in line mode and cnt > 256 (BUFINCR) cnt = BUFINCR
    the next time cnt is the value of the bytes that are not read yet, so the old value minus the line (until CR LF) or if cnt (256) is reached.
    with this solution the program does not try to allocate the whole file but for the max of 256.
    in CCGByteStreamFileSupprt.c row 705
     if(linemode && (cnt>BUFINCR)){
       cnt = BUFINCR;
    don't use the count input when using the vi in line mode. count does not make sense, cnt will be the total file size. also the output will be an array.
    linemode seems to be the value of the file size but I checked this and it is just 0 or 1, so this is good
    update: damn it doesn't work!
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

  • Trying to parse a file-read from text file.vi

    I'm attempting to read a txt file that has tab separated data. In the fourth (or any) column is the only data I need. The data is a string of numbers (23.454).
    I've used the Read from Text File.vi and the Read From Spreadsheet.vi and I just don't seem to have enough LV background to extract the pertinent  data into a graph. any suggestions?

    (It is silly to use "delete from array" if all you want is a column. The correct function is "index array")
    Joe's idea above basically works fine. Here's a quick adapdation (the node before the graph is "index array" from the array palette.).
    Message Edited by altenbach on 06-11-2007 11:57 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FileRead.png ‏11 KB

  • Set a timeout for "read from text file"

    I Need to read from a text file on a remote pc and use the read from text file function to do this. It wotks but sometimes this pc is down causing long wait times in my vi.
    Is there a way to set a timeout for the read from text file function, or is there an other solution?
    Thank you

    You could check that the path is valid first before you attempt to read the file.  hen put the file read in a True-False case structure based on the results of the check.  You can use the function "Check if File or Folder Exists"  It checks whether a file or folder exists on disk at a specified path. This VI works with standard files and folders as well as files in LLB files.   The function is found in the File I/O --> Advanced File Functions palette.
    Tom

  • 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' erases the file

    I am trying to read text in from a text file.  This is the exact code I am using.  For some reason the output from 'read from text file' contains all the text that was originally in the file, but after the code executes the file is empty.  I have several other vi's which use the same code and the file is fine.  But whenever I run this code in this one specific vi the text file gets erased.

    What is in the rest of that "specific vi"? I just tried the code you show, in v2011, and it works as expected, doesn't clear file.
    What version are you running? Can you add an error out, or make sure error output is on in your LabVIEW configuration?
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

Maybe you are looking for