Reputation: 1968
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
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
Reputation: 650
You could try a JFileChooser.
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
Upvotes: 0
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