yourselvs
yourselvs

Reputation: 451

How can I get the filepath where my project is stored from inside the project?

I'm working on a project for school that needs to read from text files inside the project directory. I have it working but only because I have the filepath hardcoded to my computer.

i.e.

String path = "C:\\Users\\MyName\\workspace\\ProjectName\\"

If I sent it to my teacher, the filepath would result in an error.

Is there a way I can set the filepath to wherever the project is stored, from inside the project?

Upvotes: 0

Views: 147

Answers (3)

copeg
copeg

Reputation: 8348

Resource files can be place relative to the class files in your project (in this manner, they can be packaged together with class files as a jar file). To access these from within your project, you can use Class.getResource() or Class.getResourceAsStream. For instance...

InputStream is = MyClass.class.getResourceAsStream('path/to/file');

Where 'path/to/file' is the path relative to where MyClass resides. Note the lack of a '/' at the beginning of this path - if it began with '/' it would be an absolute path relative to the highest package level of the project. Also note that one can use a relative file path to read a file external to the class package directory structure.

Upvotes: 1

MightyBurn
MightyBurn

Reputation: 1

Just do WhateverNeedsAPath("Something") //path will be whereever/ProjectName/Something

This might help you also: How to define a relative path in java

Upvotes: 0

Daniel Vieira
Daniel Vieira

Reputation: 32

Just put the file name.

String path = "XPTO.txt"

This means your file is in the project root.

Upvotes: 1

Related Questions