3 Replies Latest reply: Jan 13, 2013 8:34 PM by EJP RSS

    Help with FileIO

    980298
      Hi.

      I have a jar file with a .class and .txt file inside and would like to read the contents of the .txt file.This works fine when the .class and .txt files are in the same location, but in this case, the .txt file is in a subfolder, and I have tried every possible way to read with no success.

      Structure of the .jar file
      - META_INF
      - resources\tiles.txt
      - Game.class>
      private void readTextFromJar(String filename) {
           String line;
           try {
                ClassLoader cl = this.getClass().getClassLoader();
                InputStream is = cl.getResourceAsStream("/resources/" + filename);
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                     System.out.println(line);
                }
           }
           catch (Exception e) {
                ref_log.addMessage("error loading file " + filename + " (" + e.getMessage() + ")");
           }
      }
      The String argument is "tiles.txt", and I have tried removing/adding slashes to the specified resources string.

      I simply get a null pointer exception.

      Anyone knows why? And why the exact same code works if I remove "/resources/" and put "tiles.txt" next to the class file? For the record. I am able to load image files from the same subfolder.
        • 1. Re: Help with FileIO
          gimbal2
          977295 wrote:
                    InputStream is = cl.getResourceAsStream("/resources/" + filename);
          Anyone knows why? And why the exact same code works if I remove "/resources/" and put "tiles.txt" next to the class file? For the record. I am able to load image files from the same subfolder.
          You may want to try:
          InputStream is = cl.getResourceAsStream("resources/" + filename);
          Using the classloader the search is already relative to the root of the classpath.

          And of course you get a NullPointer because the InputStream reference returned contains null, but your code assumes it is not. Which is fine, that's an assumption you can make as soon as you fix the minor path thing.
          • 2. Re: Help with FileIO
            980298
            Hi and thanks for the reply.

            I tried without the leading slash, but getting the same negative result:\

            Could it be security related? Wouldnt think so, as I'm only trying to access files within the rar. But cant think of anything else, and I'm not very experienced with applets.
            • 3. Re: Help with FileIO
              EJP
              Please post the result of jar tvf xxx.jar /resources/<file name>.