0

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?

3
  • 1
    coderanch.com/t/264434/java-programmer-SCJP/certification/… - that should help you Commented Mar 24, 2015 at 22:26
  • String path = System.getProperty("user.dir"); Commented Mar 24, 2015 at 22:30
  • 1
    FYI slash works just fine, Java will convert to Windows' backspash C:/Users/... Commented Mar 24, 2015 at 22:30

3 Answers 3

1

Just put the file name.

String path = "XPTO.txt"

This means your file is in the project root.

Sign up to request clarification or add additional context in comments.

2 Comments

Will this also work if my file is in a subdirectory instead of the project root, and then adding the subdirectory in front of it?
Yes works too. Do not forget to make the scape for "/".
1

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.

3 Comments

I'm confused by what you mean when you say 'path/to/file'. If I put the project's filepath there, would the filepath not change when I send it to my teacher? And then I would have the same problem.
@yourselvs read the link I commented on your question to see the difference between relative (related to where your project is) and absolute (related to the root of the file system - "C:\" in your case) file paths.
You are reading the file RELATIVE to where the class is (as opposed to absolute as your initial post is suggesting you are doing). See the link @soong provided.
0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.