1

I have exported a project to a runnable JAR in eclipse. There are a few places in my code where I've done the following.

String file = "src/Files/...";
loadFile(file); // purely for example

Now that the project is in the form of a JAR, those directories don't seem to exist and loading those files fails. I'm pretty sure that the files I'm referencing are packed in the JAR. Do the directories change in any particular way when exported to JAR? Any other ideas on how to make this work?

icedwater
  • 4,701
  • 3
  • 35
  • 50
well actually
  • 11,810
  • 19
  • 52
  • 70
  • You can open your .jar file in a zip program to see if all the files where exported correctly. You also might want to take a look at using classpath:// for your filepaths. This post might also be helpful. http://stackoverflow.com/questions/423938/java-export-to-an-jar-file-in-eclipse – heldt Apr 03 '11 at 00:21

1 Answers1

7

You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.

Assuming that you've a foo.txt file in package com.example, then you can get an InputStream of it as follows

InputStream input = getClass().getResourceAsStream("/com/example/foo.txt");
// ...

Or when you're inside static context

InputStream input = SomeClass.class.getResourceAsStream("/com/example/foo.txt");
// ...

Or when you want to scan the global classpath

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/com/example/foo.txt");
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks. That worked for all the FileStreams. What if I need to use a BufferedWriter? – well actually Apr 03 '11 at 01:19
  • @Charlotte: Wrap an InputStreamReader + BufferedReader around your InputStream. – Paŭlo Ebermann Apr 03 '11 at 01:53
  • You can indeed get a `Reader` out of it using `InputStreamReader`. However, you cannot write to it. There are other solutions, depending on the functional requirement. Feel free to ask a new question about this. – BalusC Apr 03 '11 at 02:37