1

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?

Lenz
  • 23
  • 4
  • 2
    This could be a possible duplicate to this question: http://stackoverflow.com/questions/6853877/reading-a-file-from-current-directory-in-java - i think you should find an answer here. It is also a very bad idea to use Dropbox for sharing your code. Try github or Bitbucket for sharing your code as it will prevent versioning problems – Supahupe Jun 16 '16 at 09:11
  • Your question is not that clear. In the topic you talk about "object streams" and at the end the question is about referencing a file without using absolute path?! And what does the compiler has to do with that? – Fabian Barney Jun 16 '16 at 09:14

2 Answers2

3

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.

vanje
  • 10,180
  • 2
  • 31
  • 47
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

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.

vanje
  • 10,180
  • 2
  • 31
  • 47