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.

Similar Messages

  • Why no simple method for reading text files

    I'd like to know, after all this time why there is no simple method of reading ext files into a string.
    Yes, yes, I know all about buffered readers, (it took me long enough to figure them out) but they are cumbersome and seem to change every release (how many file methods have been deprecated...)
    Here's what I'm looking for:
    file.open();
    file.read(String);
    file.close();
    No single character at a time, no loop - the whole file into a single string in one shot. If buffers are used, i want it hidden.
    Perl, PHP, VB, C# all have this. Even Java has it when you write to a file.
    So why not on read?
    Yes, buffered streams are very elegant, but for what most programmers want to do, they are overkill and annoying.

    Just Dennis Ritchie's little joke.
    Do you have a better reason for wanting the feature
    other than that some other languages have it?Yes. It would save me time and help dozens of new programmers who continually ask this question in this and other forums. It is in other languages because people use it and want it - clearly Jarkata saw the need. If you don't like the idea, then I won't argue the point. We agree to disagree.
    Also did you have an answer for my question?in java.io.file you can do the following: (i've used it, it works) Granted, you still have to use the buffered output streams, which in my opinion should be abstracted for a simple text read and write.
    BufferedWriter outputStream = new BufferedWriter(new FileWriter(fileNewPath));
    outputStream.write(fileContent);
    outputStream.close();

  • 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

  • How to create a method for reading a file

    i tried to make it as static method for reading a file and
    then to return string
    is this code correct?
              public static String fileMaterial(String fileName)
                   fileReader = new BufferedReader(new FileReader(fileName));
                   info = fileReader.readLine();
                   while(school != null)     {                    
                        return info;
                        info = fileReader.readLine();

    I created a class you might want to look at. I come from a world of C and love fgets() and other FILE stream functions. I created a class that uses the Java I/O buts to the calling application behaves like fgets and such. The block of code where I do the calling in the calling program even looks like C. In my class I capture almost all errors and set error buffers to the errors. The calling program looks at the return to see if it succedded or errored.
    BuffIO new = BuffIO.fopen("fiilename", "r");
    String s;
    if((s = new.fgets()) == null)
    System.err.println("error reading file: " + new.ferror());
    That would be waht the calling program does

  • Reading text file and output (to stdout) a list of the unique words in the

    Hi,
    I have a main method as
    main.java
    package se.tmp;
    public class Main
    public static void main( String[] args )
    WordAnalyzer.parse( args[0] );
    and text file as
    words.txt
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the quick brown fox jumps over the lazy dog
    the requirement is like
    I need create this WordAnalyzer class, implement the parse method, and then commit the file. This method takes a single parameter, the filename of the file to parse. The method should read this file and output (to stdout) a list of the unique words in the file along with the number of times each appears in the file.
    Can anyone please help me on this?
    Thanks.

    Where are you having problems?

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

  • Can I save and read text files on a server that I host?

    Hello everyone,
    I am a java hobbiest. I was wondering if I set up my own server, running out of my house, could I have my applets save to my computer and read from my computer without having to learn JDBC and a DATABASE language. In other words could i just have my applet save and read text files from and to my server?
    I'm trying to set up a sight for my 5th grade class where parents can log into. Thanks for your time.
    Oh yeah, which is easier, learning how to set up a server or learning JDBC and a DATABASE language?
    If you have any other good idease please tell me them
    Thank you, Bryan

    Short answer: This isn't gonna work
    Long answer: For this to work, the first thing you're going to need is a static IP address and a DNS name registered -actually you don't necessarily need #2 but you're probably gonna want it and it's by far the easier of the steps.
    As far as I know to get a fixed IP address you've either gotta be directly attached to a larger network (ie university network) or get a leased line from an ISP.
    Once you've got that done come back to us.

  • How to find the arguments of a static method from the class file

    Hi,all !
    How to find the arguments of a static method from the class file? for example, when we meet a bytecode "invokestatic", how can I know the arguments of this static method?

    Hi,all !
    How to find the arguments of a static method from the
    class file? for example, when we meet a bytecode
    "invokestatic", how can I know the arguments of this
    static method?You mean
    1. The values?
    2. Argument names?
    3. Argument signatures.
    I would suppose for the last that the easiest way would be to parse the signature string.
    The first is not possible - not from the class file.
    The second is only in the debug information stored in the optional part of the class file. And figuring out the format for that is going to be a problem.

  • To read text file using utl_file

    I would like to read test_file_out.txt which is in c:\temp folder.
    create or replace create or replace directory dir_temp as 'c:\temp';
    grant read, write on directory dir_temp to system;
    then when i execute the below code i get the error .
    // to read text file using utl_file
    DECLARE
    FileIn UTL_FILE.FILE_TYPE;
    v_sql VARCHAR2 (1000);
    BEGIN
    FileIn := UTL_FILE.FOPEN ('DIR_TEMP', 'test_file_out.txt', 'R');
    UTL_FILE.PUT_LINE (FileIn, v_sql);
    dbms_output.put_line(v_sql);
    UTL_FILE.FCLOSE (FileIn);
    END;
    ERROR:
    invalid file operation
    i would like to use ult_file only and also can you let me know to read the text file and place its contents in tmp_emp table?

    Are you trying to read the contents of the file into the local variable? Or write the contents of the local variable to the file?
    Your text talks about reading the file. And you open the file in read mode. But then you call the UTL_FILE.PUT_LINE method which, as SomeoneElse points out, attempts to write data to the file. Since the file is open in read-only mode, you cannot write to the file.
    If the goal is really to read from the file, replace the UTL_FILE.PUT_LINE calls with UTL_FILE.GET_LINE. If the goal is really to write to the file, you'll need to open the file in write mode ('W' rather than 'R' in the FOPEN call).
    Justin

  • How to read text file efficiently?

    I use CharBuffer to read text file:
    private List<String> load() throws IOException {
            final String B = "<BODY>";
            final String E = "</BODY>";
            List<String> docs = new ArrayList<String>();
            for (File file : files) {
                FileReader reader = new FileReader(file);
                CharBuffer buffer = CharBuffer.allocate(BSIZE);
                StringBuilder sb = new StringBuilder();
                while (reader.read(buffer) != -1) {
                    char[] dst = new char[buffer.length()];
                    buffer.get(dst);
                    sb.append(dst);
                    buffer.clear();
                String s = sb.toString();
                System.out.println(file + ": " + s.length());
                int start = 0;
                int i, j;
                while ((i = s.indexOf(B, start)) != -1) {
                    j = s.indexOf(E, i + B.length());
                    docs.add(s.substring(i + B.length(), j));
                    start = j + E.length();
                    //System.out.printf("%d %d %d%n", i, j, start);
            return docs;
        }The file size is 1324350, but the code say it is 772802.
    What's wrong with this code?
    I want to read text file as quickly as possible.
    Is this code the right way to read file?
    Should I use FileReader or nio Channel and ByteBuffer?
    Any suggestions are welcome!

    You are reading the file as if it were encoded in UTF-16. Each character uses two bytes so you have half the number of characters as you had bytes.
    The following code reads an entire file in one hit.
        public static String readText(File file) throws IOException {
            byte[] bytes = new byte[(int) file.length()];
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            try {
                dis.readFully(bytes);
            } finally {
                dis.close();
            return new String(bytes, "UTF-8"); // or whatever your file encoding is.
        }But you can still have less characters than bytes if there are any non ASCII-7 characters.

  • How to read text file?

    Dear Everyone
    I have coding below.
    {color:#3366ff}*Text file scores.txt*
    {color}1 1 1
    2 2 2
    *{color:#3366ff}Java class jtableone.class{color}*
    import javax.swing.*;
    public class jtableone extends JApplet {
    public static void main(String[] args) throws Exception {
    {color:#ff0000}//Read file scores.txt{color}
    java.io.File file = new java.io.File("scores.txt");
    Scanner input = new Scanner(file);
    while (input.hasNext()){
    String id = input.next();
    String firstname = input.next();
    String lastname = input.next();
    {color:#ff0000}//System.out.println(id +" "+ firstname +" "+ lastname);
    {color}}
    input.close();
    {color:#ff0000}//Crearte JTable{color}
    private String[] columNames =
    {"ID", "First Name", "Last Name"};
    private Object[][] data = {
    //{"12", "Tom", "Clark"},
    //{"13", "helen", "Tan"}
    {color:#ff0000}//Display JTable{color}
    private JTable jTable1 = new JTable(data, columNames);
    public jtableone(){
    add(new JScrollPane(jTable1));
    Can you tell me What i do next?
    Create a Object[][] data which can read text file.
    Thanks
    sevenlon

    sevenlon wrote:
    Can you tell me What i do next?How are we supposed to know? We have no knowledge of what your assignment is.
    Create a Object[][] data which can read text file.Then do that. Create the 2D array and store the data in it.
    Also when posting code use code tags. Paste code, highlight it and click CODE button.

  • Reading text file to JEditorPane

    Hi,
    I'm trying to read text file to JEditorPane and it works but first line is always missing. Here is the code for reading:
    try {
       in = new BufferedReader(new FileReader(filePathIn));
       while ((lineIn = in.readLine()) != null) {
            editorPane.read(in, new Object());
    } catch (IOException ie)...Any suggestions?

    in.readLine is changing the input stream position.
    Do this instead:
    FileInputStream in = new FileInputStream(filePathIn);
    while (in.available() != 0)
        editorPane.read(in, new Object());

  • In 10g read text files

    i am not able to read text file in 10g forms. using webutil.pll and webutil.lib
    here i posted the code . i am not getting message 2, client_text_io.fopen is not working what could be the reason.
    DECLARE
    in_file client_TEXT_IO.FILE_TYPE;
    V_LINE_COUNT number;
    linebuf VARCHAR2(1800);
    V_var1 varchar2(80);
    V_var2 varchar2(80);
    V_var3 varchar2(80);
    V_var4 varchar2(80);
    V_var5 varchar2(80);
    filename VARCHAR2(30);
    l_var number;
    blnRet BOOLEAN;
    begin
         DELETE FROM NIRU_TEMP;
    :file_path:=LTRIM(RTRIM(:file_path));
    MESSAGE('1');
    in_file := client_text_io.fopen(UPPER(:file_path),'r');
    MESSAGE('2');
    loop
    V_LINE_COUNT := V_LINE_COUNT + 1;
    client_text_io.get_line(in_file,linebuf);
    MESSAGE('5');
    V_var1 := substr(linebuf,1,(instr(linebuf,',')-1)) ;
    MESSAGE('6'||V_VAR1);
    MESSAGE('6'||V_VAR1);
    l_var := length(v_var1);
    V_var2 := substr(linebuf,l_var+2,(instr(linebuf,','))) ;
    --V_var3 := substr(linebuf,15 ,10 );
    V_var2 :=LTRIM(RTRIM(V_var2));
    MESSAGE('6'||V_var2);
    MESSAGE('6'||V_var2);
    :p_id := v_var1;
    :p_desc :=v_var2;
    --IF V_var2 = '' THEN
    --V_var3 :='';
    --else
    --V_var3 := TO_NUMBER(V_var2) ;
    --end if;
    --V_var5 := substr(linebuf,26 ,70 );
    INSERT INTO NIRU_TEMP VALUES (V_var1,V_var2);
    client_text_io.new_line;
    :System.Message_Level := '20';
    commit;
    :System.Message_Level := '0';
    --<<end_loop>>
    --null;
    next_record;
    end loop;
    client_TEXT_IO.FCLOSE(in_file);
    exception
         WHEN OTHERS THEN
         MESSAGE('ERROR'||SQLCODE||' '||SQLERRM);
    --exit;
    end;

    Hello Francois,
    You have a solution for this problem?
    I have a problem like this. While reading a text file, such as size of 7MB, long, between 15-30 minutes.
    See...
    declare
         arq client_text_io.file_type;
         linha varchar2(800);
         v_total number := 0;
         v_icms number := 0;
    begin
    :valor_total := 0;
    :valor_icms := 0;
         arq := client_text_io.fopen(:arquivo,'r');
         loop
         client_text_io.get_line(arq,linha);
         if substr(linha,1,1) = '1' then
              v_total := v_total + (to_number(substr(linha,302,13))/100);
              v_icms := v_icms + (to_number(substr(linha,262,13))/100);
         end if;     
         end loop;
         client_text_io.fclose(arq);
         exception
              when no_data_found then
              :valor_total := v_total;
              :valor_icms := v_icms;
              message('Realizado com sucesso!');
              message('Realizado com sucesso!');
    end;

  • How to read text file content in portal application?

    Hi,
    How do we read text file content in portal application?
    Can anyone forward the code to do do?
    Regards,
    Anagha

    Check the code below. This help you to know how to read the text file content line by line. You can display as you require.
    IUser user = WPUMFactory.getServiceUserFactory().getServiceUser("cmadmin_service");
    IResourceContext resourceContext = new ResourceContext(user);
    String filePath = "/documents/....";
    RID rid = RID.getRID(filePath);
    IResource resource = ResourceFactory.getInstance().getResource(rid,resourceContext);
    InputStream inputStream = resource.getContent().getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = reader.readLine();
    while(line!=null) {
          line = reader.readLine();
         //You can append in string buffer to get file content as string object//
    Regards,
    Yoga

  • How can I read text files from LAN if I only know the hostname?

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    <p>1. How can I read text files from LAN if I only know the hostname, or IP address?
    <p>2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.
    (ex. how can I read the 120th line?)
    <p>Please help!
    <p>sorry for the bad english

    I'm new in Java Developing, and dont know the written classes yet. I need help, how to do the following steps?
    1. How can I read text files from LAN if I only know the hostname, or IP address?You need to know the URL of the file. You need to know the hostname, port, protocl and relative path.
    The hostname is server, not file.
    2. How to read lines from text files without read all lines from the beginning of file, just seek to a position.Use the seek() to get to a random byte.
    (ex. how can I read the 120th line?)The only way to find the 120th line is to read the first 120 lines. You can use other file formats to find the 120th line without reading the whole file but to need to be able to detremine where the 120th line is

Maybe you are looking for

  • What is the best media player supported for my nok...

    Suggest me best media player which can play all formats of audio and video and where can i download it?

  • Since donwloading iOS 6

    my apps crash constantly even when i'm searching for apps on the app store. apple can you please work on this?

  • How do I switch to another window in Firefox for Mac?

    I often have multiple Firefox windows open. Does Firefox or Mac OS X provide a way to switch among windows? Normally I can switch from one window to another by Command-Tab, but when I have multiple Windows open for one application (such as Firefox),

  • Shrill stuttered white noise freeze/crash??

    I only get this when Logic is running. There doesn't even have to be much of anything going on. Maybe one synth or Kontakt open. Point and click on something and whammo....scares me every time. It sounds like crackling sizzling white noise screeching

  • Sound card for E250

    Hello all Does any one know off a sound card that is supported by Solaris on a E250. Or any way of getting sound off the E250? Thanks