Talen Kylon
Talen Kylon

Reputation: 1968

Is there a way to read a file that's within our project without needing a hardcoded path?

I have a few .dat files that my program reads for input and output. They are stored in the project folder. How would I read and write to these files, what would the path be?? I'd like to be able to zip up the project and send it off for others to use so I can't hard code a path because others may not place it in the same path

Right now I'm using the Scanner and File classes:

    String input= "E:\\CProj01\\input.dat";
    Scanner scannerInput = new Scanner(new File(input));

Upvotes: 0

Views: 81

Answers (3)

andrewdleach
andrewdleach

Reputation: 2466

Yes! You can use a ClassLoader

If you keep your files located in a relative place within the directory of your project, you can do something like this:

getClass().getClassLoader().getResourceAsStream("relative file path here")

And then you can use the returned InputStream object to parse the file.

The ClassLoader allows you to keep all your files relative to the Project Root so if you had files organized like so:

src_
    |___files_
    |    -'yourfile.dat'
    |    -'anotherfile.dat'
    |___java_

Referencing yourfile.data with the String argument of files/yourfile.dat would always get you that file as a stream no matter where the package is deployed/downloaded/moved to.

Upvotes: 3

Zach
Zach

Reputation: 650

You could try a JFileChooser.

https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

Upvotes: 0

Tom C
Tom C

Reputation: 814

Yes, if you're sending it as Java project which they can use and edit then you can create a resources folder and you can simply get the file path like

String input= "src/resources/input.dat";
Scanner scannerInput = new Scanner(new File(input));

Upvotes: 1

Related Questions