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?

yourselvs
  • 411
  • 1
  • 3
  • 7

3 Answers3

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.

copeg
  • 8,290
  • 19
  • 28
  • 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 Mar 24 '15 at 22:31
  • 1
    @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. – childofsoong Mar 24 '15 at 22:34
  • 1
    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. – copeg Mar 24 '15 at 22:35
1

Just put the file name.

String path = "XPTO.txt"

This means your file is in the project root.

0

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

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

Community
  • 1
  • 1