Take the 2-minute tour ×

Ok so I have a project in eclipse called SWT. In one of the classes in this project there is a code:

public static String rpath = "..\\SWT\\src\\data.txt";
public static String path = new File(rpath).getAbsolutePath();

If I compile and run my project in eclipse, my program is able to find data.txt and use it as input, which is the file's intended purpose.

I then export this project to an executable jar file, open the command prompt and enter java -jar SWT.jar. the program opens but in the command prompt, there is the following error:

java.io.FileNotFoundException: C:\Users\Yoshikawa\workspace\SWT\..\data.txt (The system cannot find the file specified)

My question:

How can I modify my code prior to exporting it to an executable jar, so that I can make my executable jar able to find the data.txt? By the way, my executable jar contains data.txt already, but is not able to use the relative path specified above to find its exact location, which I find very very odd.

share|improve this question

3 Answers 3

There will be no src directory in your jar file. Only the package names and class files.

share|improve this answer

Try this:

URL url = ClassLoader.getSystemResource("/data.txt");
File file = new File(url.toURI());

More info here.

share|improve this answer
Where do I add these two lines of code? Do I add delete the two lines I have above and replace them with this, or do I add it in addition to this? And also does I want the file path it gets to be in string format. –  nbhgt Apr 12 '13 at 21:17

You can put the file, data.txt, at some package and then use a class from this package to do this:

URL url = ClassFromSamePackageOfFile.class.getResource( "data.txt" );

File f;
try {
  f = new File(url.toURI());
} catch(URISyntaxException e) {
  f = new File(url.getPath());
share|improve this answer

Your Answer


