Lenz
Lenz

Reputation: 23

Sharing a Java Object Stream

I've got a project to do with 2 other classmates. We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)

My question is now about sharing the object stream. I want to put the file of the stream in same dropbox shared directory of the code. BUT, when i initialize the file

File f = new File(PATH);

i must use the path of my computer (C:\User**Alessandro**\Dropbox) As you can see it is linked to Alessandro, and so to my computer. This clearly won't work on another PC. How can tell the compiler to just look in the same directory of the source code/.class files?

Upvotes: 1

Views: 86

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:

URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());

Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.

Upvotes: 3

vanje
vanje

Reputation: 10373

Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.

As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.

Upvotes: 2

Related Questions