Page 1 of 2 12 LastLast
Results 1 to 20 of 26
  1. #1
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Reading files in JARs from an applet

    Basically, I've got this setup: A JAR files containing the normal class-files, a bunch of images and a text file that points to the images. When I run it as a frame (I've got two entry-points; one for applets and one for "normal" running), everything works as it should; it reads the text file from the JAR and loads the images, all fine. However, when I try to run it as an applet, it simply refuses to read the textfile unless it's outside of the JAR-file (at which point it reads the images inside the JAR without a problem). I've googled a bit and found a few pieces of code that apparently should fix the problem... but no such luck. Here's a few of the attempts I've made to read the file (the first and last works with the target file outside of the JAR, but not with it inside, and the middle just returns null, more or less as I expected it to):
    Java Code:
      public InputStream getInputStreamForFile(String path) throws MalformedURLException, IOException
      {
    //    return getClass().getResourceAsStream(path);
    //    return ClassLoader.getSystemResource(path).openConnection().getInputStream();
        return new URL(getCodeBase(), path).openConnection().getInputStream();
      }
    I call it thusly (from another class):
    Java Code:
          InputStream is=head.getInputStreamForFile("testfile.txt");
    Here's another funky bit: If I change it to "/testfile.txt", it reads the textfile as it should, but it stops the (completely unrelated) image loading from working! Any suggestions?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    when I try to run it as an applet, it simply refuses to read the textfile
    Could you make a small simple applet that demonstrates the problem?
    And a batch file to create the jar file.
    And the html to execute it.

  3. #3
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Okay, here's a very boiled down version of it that demonstrates the problem (the two methods I'm using here are the ones I've found through Google).
    PHP Code:
    package failtest;
    
    import java.applet.Applet;
    import java.net.URL;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.InputStream;
    
    public class FaultyReading extends Applet
    {
      public void init()
      {
        System.out.println("First method");
        System.out.println("============");
        try
        {
          URL u=new URL(getCodeBase(), "readtest.txt");
          BufferedReader in=new BufferedReader(new InputStreamReader(u.openConnection().getInputStream()));
          System.out.println(in);
          System.out.println(in.readLine());
        }
        catch (Exception e)
        {
          System.out.println(e+"\r\n"+e.getMessage()+"\r\n");
          e.printStackTrace();
        }
        System.out.println();
        System.out.println("Second method");
        System.out.println("=============");
        try
        {
          BufferedReader in=new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("readtest.txt")));
          System.out.println(in);
          System.out.println(in.readLine());
        }
        catch (Exception e)
        {
          System.out.println(e+"\r\n"+e.getMessage()+"\r\n");
          e.printStackTrace();
        }
      }
    }
    Java Code:
    @copy /Y *.class failtest\
    @jar cvf "FaultyReading.jar" failtest\ readtest.txt
    PHP Code:
    <HTML>
    <BODY>
    <applet code="failtest/FaultyReading.class"
            archive="FaultyReading.jar"
            width=200 height=100>
    </applet>
    </BODY>
    </HTML>
    This produces the following error (roughly translated)
    Java Code:
    First method
    ============
    java.io.FileNotFoundException: C:\Java\AppletTest\jar\readtest.txt (Cannot find the file)
    C:\Java\AppletTest\jar\readtest.txt (Cannot find the file)
    
    java.io.FileNotFoundException: C:\Java\AppletTest\jar\readtest.txt (Cannot find the file)
            at java.io.FileInputStream.open(Native Method)
            at java.io.FileInputStream.<init>(FileInputStream.java:106)
            at java.io.FileInputStream.<init>(FileInputStream.java:66)
            at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:70)
            at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:161)
            at failtest.FaultyReading.init(FaultyReading.java:18)
            at sun.applet.AppletPanel.run(AppletPanel.java:424)
            at java.lang.Thread.run(Thread.java:662)
    
    Second method
    =============
    java.lang.NullPointerException
    null
    
    java.lang.NullPointerException
            at java.io.Reader.<init>(Reader.java:61)
            at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
            at failtest.FaultyReading.init(FaultyReading.java:32)
            at sun.applet.AppletPanel.run(AppletPanel.java:424)
            at java.lang.Thread.run(Thread.java:662)

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    The program appears to want to read from the disk, not the contents of the jar file.
    Print out the codebase and the url. They both point to the local disk.

    To read from a jar file I've always used getResourceAsStream()
    Look in the jar file with a zip utility to be sure the file is on the path you think it should be

  5. #5
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Got any tips for finding out where it looks for it? When reading images in applets and all files in applications, it seems to be based on the root of the JAR file (which is where readtest.txt is). That is, obviously, not the case here though...

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    where it looks for it
    I think it depends on the class.
    For testing I had two txt files with different identifying contents, one in the jar and one in the folder with the html file: ForTesting

    The java console:

    Java Plug-in 1.6.0_20
    Using JRE version 1.6.0_25-b06 Java HotSpot(TM) Client VM
    User home directory = C:\Documents and Settings\Owner

    First method
    ============
    CodeBase=file:/D:/JavaDevelopment/Testing/ForumQuestions5/ForTesting/
    u=file:/D:/JavaDevelopment/Testing/ForumQuestions5/ForTesting/readtest.txt
    java.io.BufferedReader@120a47e
    This is at the level with the html

    Second method
    =============
    in=java.io.BufferedReader@f73c1
    first ln=From the jar file

  7. #7
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Hard to say from that, but I assume you put the file in the root of the jar in the second case (where mine is)? If so, it's back to square one, basically... I wonder how much I can cheat with loading images that contain the text in their pixels. At least I know I can load those

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    The txt in the jar file was in the failtest folder, not the root folder.

    With this kind of testing, put different versions of the file(same name) in all the possible places. When you read it, display its contents which should say where it was located.

  9. #9
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Putting it all into the folder with all the .class files seems to work for the applet. Too bad that means I have to keep doubles of all the images in the JAR, but hopefully I'll be able to sort that out later on... At least it works for now. Thanks!

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    Try some more experiments. For example
    remove the package statement.
    Use a path beginning with a /

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    Try adding this:


    System.out.println("gR=" + getClass().getResource("/"+FN));
    //gR=jar:file:/D:/JavaDevelopment/Testing/ForumQuestions5/ForTesting/FaultyReading.jar!/failtest/readtest.txt w/o "/"
    //gR=jar:file:/D:/JavaDevelopment/Testing/ForumQuestions5/ForTesting/FaultyReading.jar!/readtest.txt << with "/"

  12. #12
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Managed to solve it just a few minutes ago, in fact! If I add slashes to the path, the applet works with everything in the root of the JAR. However, the application part won't work. Without slashes, the applet have to have the resources in the folder with the .class files, meaning I'd need double of everything (one set in the root for the application, one set in the .class folder for the applet). Right now I'm using paths without slashes, but in the applet handler part I prepend a single slash to the path whenever I need to read something. Not sure if there are any long-term problems with that, but at least it's working for now.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    What do you mean by "the application won't work"?
    Are you not running the desktop app via a jar?

  14. #14
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Yeah; I've got both the applet and the application in the same JAR file. If I added a slash to all the paths, the application part wouldn't find the files anymore.

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    So presumably getResource returns a different value for each of them?
    Have you tried to print that out to see where it thinks "/yourfile" is when the jar is run as an app compared to where it thinks it is when run as an Applet?
    The stuff after the "!" should be identical.

  16. #16
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    As I said above, it's solved, but when I couldn't read the file, it actually returned null. So finding out where it was trying to find the file that way didn't work.

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,317
    Rep Power
    25

    Default

    If I added a slash to all the paths, the application part wouldn't find the files anymore.
    Are the app and the applet in the same package?
    The classloader is involved when you use getResource() and will use the package as part of the path to the file. The "/" will go to the root.

  18. #18
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Everything is part of the same package, yeah. I use a slightly different method for loading files when in app-mode though (ClassLoader.getSystemResource(path).openConnectio n().getInputStream() as opposed to getClass().getResourceAsStream(path) for applets). Could be why it's getting confused, I suppose, but the ClassLoader part suggests the classloader is involved there as well (the documentation doesn't say much about it other than it uses getSystemClassLoader).

  19. #19
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default

    getResource and getResourceAsStream both do some work on the name you pass in before handing off to the ClassLoader.getSystemResource().
    Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
    If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
    etc etc
    Last edited by Tolls; 06-16-2011 at 04:57 PM. Reason: Missed a bit in the quote

  20. #20
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default

    Yeah, I found the part about the slash early on and tried it, but it didn't work as well with the application part of the code. At the moment, I only apply it to the applet part of the code, which means it's working right now. Hard to say if it'll give me any nasty surprises in the future, but considering that part of the code is rather small (it's basically only a single line that returns an input stream), I hope it'll hold together.

Page 1 of 2 12 LastLast

Similar Threads

  1. reading files from online applet
    By mickmos in forum Java Applets
    Replies: 0
    Last Post: 12-02-2010, 01:21 AM
  2. Reading external text files from an Applet
    By Arnold in forum New To Java
    Replies: 2
    Last Post: 01-07-2010, 06:43 PM
  3. Reading/Writing files through Applet
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 03-09-2009, 11:45 AM
  4. Replies: 0
    Last Post: 02-26-2009, 03:13 AM
  5. Applet - reading text files packed into JAR file
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 09:15 AM

Posting Permissions

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