×

Discussion Board

Results 1 to 2 of 2
  1. #1
    Regular Contributor
    Join Date
    Mar 2003
    Posts
    60

    reading text file from a jar file -> file not found!

    hello,

    i want to read a txt file from jar file
    im using the following code
    the file "level01.txt" is in the jar file - checked via zip
    and was placed in a subfolder called "res"
    the jarfile was created using jbuilder 5

    my problem: my code cant find the file?
    error >> java.lang.NullPointerException
    ive tried different path/filename versions
    such as:
    "level01.txt"
    "/level01.txt"
    "/res/level01.txt"


    does anybody have any idea?
    thanks for any help
    andreas


    my code
    =======

    try {
    InputStream is = this.getClass().getResourceAsStream("/level01.txt"
    StringBuffer sb = new StringBuffer();
    int chr;
    while ((chr = is.read()) != -1)
    {
    sb.append((char) chr);
    is.close();
    }
    System.out.println(" > reading OK!"
    }
    catch (Exception e)
    {
    System.out.println(" > ERROR: Cant Read File ERR= " + e);
    }

  2. #2
    Regular Contributor
    Join Date
    Mar 2003
    Location
    UK
    Posts
    229

    RE: reading text file from a jar file -> file not found!

    Hi,

    Your while loop is incorrect. You have the is.close() inside the loop, so it will occur straight after the first character is read, then the next read() will throw an exception!

    Any of the path names should work. eg, if file in jar="/res/level01.txt" then them do getResourceAsStream("/res/level01.txt&quot.

    The loop you want is:

    while ((chr = is.read()) != -1)
    {
    sb.append((char) chr);
    }
    is.close(); // NOTE OUTSIDE LOOP :-)

    Hope this helps,

    Steve

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×