13 Replies Latest reply on Jun 1, 2009 3:59 PM by camickr

    Accessing a text file in a jar

    camickr
      I want to read a text from from a jar and display it in a text area. The basic code is:
      JTextArea textArea = new JTextArea(10, 50);
      JScrollPane scrollPane = new JScrollPane( textArea );
      File file = ???:
      FileReader reader = new FileReader( file );
      BufferedReader br = new BufferedReader(reader);
      textArea.read( br, null );
      br.close();
      I've tried:
      URL url = AlphaContainerTest.class.getResource("AlphaContainerTest.java");
      File file = new File( url.toURI() );
      which results in:

      java.lang.IllegalArgumentException: URI is not hierarchical

      I've also tried:
      File file =  new File(getClass().
          getResource("AlphaContainerTest.java").getFile());
      which results in:

      java.io.FileNotFoundException: file:\C:\Java\blog\AlphaContainer.jar!\AlphaContainerTest.java (The filename, directory name, or volume label syntax is incorrect)

      Either of the above approaches works fine when not using the jar file.

      In case it matters here the the output from the creation of the jar file:
      C:\Java\blog>jar cfev AlphaContainer.jar AlphaContainerTest 
          AlphaContainer*.class AlphaContainerTest.java
      added manifest
      adding: AlphaContainer.class(in = 837) (out= 514)(deflated 38%)
      adding: AlphaContainerTest$1.class(in = 442) (out= 306)(deflated 30%)
      adding: AlphaContainerTest$2.class(in = 1819) (out= 1032)(deflated 43%)
      adding: AlphaContainerTest.class(in = 2265) (out= 1293)(deflated 42%)
      adding: AlphaContainerTest.java(in = 2329) (out= 945)(deflated 59%)
      What is the proper way to read a text resource from a jar file?
        • 1. Re: Accessing a text file in a jar
          807588
          Try this: [http://java.sun.com/developer/JDCTechTips/2003/tt0122.html]
          It looks promising, I haven't gotten to use java.util.jar yet. ;)
          • 2. Re: Accessing a text file in a jar
            807588
            what about using an inputstreamreader rather than a filereader because you're not really reading a file?

            Note: I"m no expert at this, so consider this a somewhat educated guess.

            For instance assuming a text file called TextFromJar.txt in the jar file in the same location as the class files:
            import java.io.BufferedReader;
            import java.io.IOException;
            import java.io.InputStreamReader;
            
            import javax.swing.*;
            
            public class TextFromJar {
              private static void createAndShowUI() {
                JTextArea textArea = new JTextArea(10, 50);
                JScrollPane scrollPane = new JScrollPane(textArea);
                
                BufferedReader br = null;
                
                try {
                  br = new BufferedReader(
                  new InputStreamReader(
                      TextFromJar.class.getResourceAsStream("TextFromJar.txt")));
                  textArea.read(br, null);
                } catch (IOException e) {
                  e.printStackTrace();
                } finally {
                  try {
                 br.close();
                  } catch (IOException e) {
                 e.printStackTrace();
                  }      
                }
                
                JFrame frame = new JFrame("TextFromJar");
                frame.getContentPane().add(scrollPane);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
              }
            
              public static void main(String[] args) {
                java.awt.EventQueue.invokeLater(new Runnable() {
                  public void run() {
                 createAndShowUI();
                  }
                });
              }
            }
            Edited by: Encephalopathic on May 31, 2009 3:30 PM
            • 3. Re: Accessing a text file in a jar
              807588
              Encephalopathic wrote:
              what about using an inputstreamreader rather than a filereader because you're not really reading a file?

              Note: I"m no expert at this, so consider this a somewhat educated guess.
              I guess this could work:

              {code}
              URL url = AlphaContainerTest.class.getResource("AlphaContainerTest.java"); // use getResourceAsStream() and InputStream inStream instead
              File file = new File( url.toURI() ); // use InputStreamReader reader = new InputStreamReader( inStream );
              {code}
              • 4. Re: Accessing a text file in a jar
                camickr
                It looks promising, I haven't gotten to use java.util.jar yet. ;)
                I guess my questions was a bit unclear. That code is for an external program trying to read from the jar. I'm trying to execute my application from within a jar and read the text file from within the jarred application. That link may come in handy in the future.
                • 5. Re: Accessing a text file in a jar
                  807588
                  scphan wrote:
                  I guess this could work:
                  URL url = AlphaContainerTest.class.getResource("AlphaContainerTest.java"); // use getResourceAsStream() and InputStream inStream instead
                  File file = new File( url.toURI() ); // use InputStreamReader reader = new InputStreamReader( inStream );
                  I wonder if you'll run into the same issue that rob's running into since it tries to force a square peg (a resource) into a round hole (a file).
                  • 6. Re: Accessing a text file in a jar
                    camickr
                    what about using an inputstreamreader rather than a filereader because you're not really reading a file?
                    I just went for a walk to clear my head and was thinking the same thing and was just starting to test it when I saw your reply. That is in fact the solution I need. The code I ended up using is:
                    JTextArea textArea = new JTextArea(10, 50);
                    JScrollPane scrollPane = new JScrollPane( textArea );
                    
                    InputStreamReader reader = new InputStreamReader(
                         AlphaContainerTest.class.getResourceAsStream( "AlphaContainerTest.java" ) );
                    BufferedReader br = new BufferedReader(reader);
                    textArea.read( br, null );
                    br.close();
                    Thanks
                    • 7. Re: Accessing a text file in a jar
                      807588
                      Cool, and you're welcome.
                      • 8. Re: Accessing a text file in a jar
                        807588
                        Encephalopathic wrote:
                        scphan wrote:
                        I guess this could work:
                        I wonder if you'll run into the same issue that rob's running into since it tries to force a square peg (a resource) into a round hole (a file).
                        I just tested it, and it doesn't work, possibly for the same reason.
                        • 9. Re: Accessing a text file in a jar
                          807588
                          Encephalopathic wrote:
                          Encephalopathic wrote:
                          scphan wrote:
                          I guess this could work:
                          I wonder if you'll run into the same issue that rob's running into since it tries to force a square peg (a resource) into a round hole (a file).
                          I just tested it, and it doesn't work, possibly for the same reason.
                          ? Sorry if it confused you but I meant replace the File line with InputStreamReader just like how camickr did his fix.
                          Grab an InputStream via getResourceAsStream(), then place it in an InputStreamReader.
                          • 10. Re: Accessing a text file in a jar
                            807588
                            InputStreamReader aside: consider using on the InputStreamReader constructors that take a second "charset name" parameter. the InputStreamReader(InputStream in) constructor will use the platform's default charset, but then you may have jarred the text file on one platform and are now trying to execute the jar on another.

                            getClass().getResource[AsStream] aside: There are several threads here that argue the correct or best practice way to do this is to use
                            Thread.currentThread().getContextClassLoader().getResource[AsStream]
                            • 11. Re: Accessing a text file in a jar
                              camickr
                              the InputStreamReader(InputStream in) constructor will use the platform's default charset, but then you may have jarred the text file on one platform and are now trying to execute the jar on another
                              The file in question is a simple Java source file saved by my editor. Does the editor used matter how the data is saved (its an old dos based editor)? How do I know what charset was used? How do I know what the default for my platform (XP) is? Do I just assume "UTF-8"?
                              There are several threads here that argue the correct or best practice way to do this is to use
                              I've seen those, I can never find them again, when I need them.
                              • 12. Re: Accessing a text file in a jar
                                807588
                                camickr wrote:
                                the InputStreamReader(InputStream in) constructor will use the platform's default charset, but then you may have jarred the text file on one platform and are now trying to execute the jar on another
                                The file in question is a simple Java source file saved by my editor. Does the editor used matter how the data is saved (its an old dos based editor)? How do I know what charset was used? How do I know what the default for my platform (XP) is? Do I just assume "UTF-8"?
                                The default encoding on *nix tends to be Latin-1, while on Windows it tends to be CP 1252.  If the file is Java source it might not make any difference. One common place where CP 1252 diverges from Latin-1 are curved quotes: (bytes 147 and 148 encoding \u201C and \u201D).
                                There are several threads here that argue the correct or best practice way to do this is to use
                                I've seen those, I can never find them again, when I need them.
                                [http://forums.sun.com/thread.jspa?threadID=5355229]

                                (I still haven't had cls.getResource break for me.)
                                • 13. Re: Accessing a text file in a jar
                                  camickr
                                  If the file is Java source it might not make any difference.
                                  Its for my blog. I added a Webstart feature that allows you to download my test code. That got me thinking. On my blog I have my standard "Get the Code" link? So I'm guessing that if you have a problem with the Webstart download charset, then you would also have a problem with the "Get the Code link".

                                  Since I've never had problems downloading Java source code from any website, I don't think I'll worry about this.

                                  In case anyone cares, here is the last blog entry on [Backgrounds With Transparency|http://www.camick.com/java/blog.html?name=backgrounds-with-transparency] that generated this question.