1

I am using an XML document as a template for multiple, similar documents (monthly reports which are organized identically). I was struggling to find the most generic path to the file. I came up with:

File f1 = new File("src/Statements/TemplateStatement.xml");

where /Statements/ is a folder under the src tab in Eclipse as if it were just another package.

Then:

File TemplateStatement = new File(f1.getAbsolutePath());
if (TemplateStatement.exists()) {
    // ...do some stuff
} else {
    JOptionPane.showMessageDialog(null, null,
            "ERROR: Transaction template not found.", JOptionPane.OK_CANCEL_OPTION);

    System.exit(0);
}

When running from Eclipse, it works great and my stuff gets done. When running as a .jar on my desktop (same machine and file system), I hit the else clause every time. I suspect I am missing a very basic yet important property of how jars package up the workspace and run it (as in there is no src directory associated with it anymore?).

I have had no luck finding examples or explanations on how to find the path, access, read, write, copy, etc. files from jarred applications. I really want to avoid hard-coding a full path as it may be the case the code will run on various machines. Any suggestions or pointers would be appreciated.

Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72
Beircheart
  • 11
  • 1
  • Welcome to StackOverflow, Beircheart. How did you create your `jar` file? Have you had a look at [this related question](http://stackoverflow.com/q/423938/983430) yet? It explains how to export your eclipse project as a `jar` file, and how to include other components. – Amos M. Carpenter Mar 25 '15 at 07:45
  • Objects in a Jar are not files and can't be accessed using `File`. Use `Class.getResource` to access jar objects. – greg-449 Mar 25 '15 at 08:11

1 Answers1

0

I've just encounted a similar problem, and it was caused by the java.io.FileReader function which uses platform default encoding.

As for my situation, in Runnable .jar running, java.io.FileReader uses ISO-8859-1 encoding, while in Eclipse it uses UTF-8 encoding. Replacing

new FileReader(filepath)

with

new InputStreamReader(new FileInputStream(filepath),  "UTF-8")

solves my problem.