Groovy Natty
Groovy Natty

Reputation: 31

System.getProperty("user.dir") alternative

I would like to write JSon files in my Java Application, it works perfectly in my IDE but as soon as I move the directory, the system fails to write the file. I eventually found the problem : The line System.getProperty("user.dir") returns a bad path.

The files are located in C:\wamp\www\myProject during development. Here is my code at the moment :

String url = System.getProperty("user.dir") + "\\src\\json\\Crc.json";
//Returns "C:\wamp\www\myProject\src\json\Crc.json"

After moving my project to C:\Users\myUser\Desktop :

String url = System.getProperty("user.dir") + "\\src\\json\\Crc.json";
//Returns "C:\Users\myUser\src\json\Crc.json"

I would like to have a way to find where my project directory is on the computer at anytime. Do you guys have a solution ?

Upvotes: 0

Views: 9947

Answers (1)

Timothy Truckle
Timothy Truckle

Reputation: 15622

The C:\wamp\www\myProject folder is just a random place on your hard disk.

Java supports 3 generic places to look for resources:

  1. the current working directory. this is where your command prompt is and what System.getProperty("user.dir") returns, but you cannot rely on that beeing somehow related to any cretain place in the file system, especially not related to the project structure on your own system.

    You should only use that if your program has a command line interface and looks for some default file name to work with.

  2. the user home This is what you get when calling System.getProperty("user.home"). On Unix this resoves to $HOME and on Windows to %USERPROFILE%.

    This is the best place for files changed at runtime or holding user specific content.

  3. the own code location. Resources in the same package as your class are accessed with getClass().getResource("filenameWithoutPath") But usually you place resources in a special folder in the application root and access it like this: getClass().getResource("/relative/path/from/src/root/filenameWithoutPath").

    In your IDE this special folder should be Project/src/main/resources (according to the maven Standard Directory Layout

    This is appropriate for some global configurations that you change when creating the delivery package.

Upvotes: 2

Related Questions