Accessing text files within a jar file

Discussion in 'Java' started by Blake Essing, Sep 11, 2006.

  1. Blake Essing

    Blake Essing Guest

    I have a simple program that uses a text file for some static data.
    When I run my program from within Eclipse or from the jar located in my
    workspace it works fine because it can find the path to my development text
    file. But I want to be able to run the jar from anywhere. How can I
    access the file from within the jar file. Important bits of code I have
    are:

    private static File mFile = null;
    private static String mBaseSolution = "../solution/Solutions.txt";

    ...

    mFile = new File(mBaseSolutions);
    if (mFile.exists()) {
    ...
    } else {
    System.out.println("Can't find solution file");
    System.exit(1);
    }

    The code fails on the mFile.exists() because it can't find the correct
    path.
    Blake Essing, Sep 11, 2006
    #1
    1. Advertising

  2. Blake Essing wrote:
    > I have a simple program that uses a text file for some static data.
    > When I run my program from within Eclipse or from the jar located in my
    > workspace it works fine because it can find the path to my development text
    > file. But I want to be able to run the jar from anywhere. How can I
    > access the file from within the jar file.


    You can get an InputStream to a file inside a jar file
    in the classpath via:

    getClass().getClassLoader().getRessourceAsStream()

    or one of the other similar variants.

    Arne
    =?ISO-8859-1?Q?Arne_Vajh=F8j?=, Sep 11, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arnold Peters
    Replies:
    0
    Views:
    568
    Arnold Peters
    Jan 5, 2005
  2. muttley
    Replies:
    0
    Views:
    2,719
    muttley
    Oct 20, 2005
  3. cyberco
    Replies:
    4
    Views:
    3,754
    Roedy Green
    Feb 14, 2006
  4. Arnold Peters
    Replies:
    0
    Views:
    657
    Arnold Peters
    Jan 5, 2005
  5. laredotornado
    Replies:
    23
    Views:
    1,277
    Arne Vajhøj
    Jan 26, 2011
Loading...

Share This Page