0

my program on startup will: 1. search for a file 2. read the file 3. and set a string to the files contents

But the way ive done it it will only work if they have the exact path that i am hard coding in. i want the path to adapt to other computers. I think i should use the Path class but ive just heard about that so not sure where to go.

basically i want it to search for a file on any users desktop, and if its not there make it.

if you need some code to clarify i can post it just let me know

Valasco
  • 3
  • 2
  • Other programs accomplish this task by having the user open a program that sets up the other files, and gives them the correct information for the path info. – FailingCoder Dec 10 '19 at 04:21
  • yes but for the program to check if the file exists, it needs a path. and that path is only for my computer... But thats what im trying to do. On startup if a path(which is saved in a txt File) does not exist, create it. but on the next statup that file is null. because the path to the file is in the file itself... if that made any sense – Valasco Dec 10 '19 at 04:35

2 Answers2

1

You can use the path "./yourfile.txt". It will search for "yourfile.txt" in the directory ".". That means the project's current directory. Maybe it can help you.

hel
  • 453
  • 4
  • 12
Altusha
  • 21
  • 4
1

I could think of two options.

You can simply specify a file name such as "myFile.txt", so the program will search this file in its program/project folder. If it does not exist you can write the code to create it in the program folder, instead of hard coding any absolute path.

Else, you can try using the javax.swing.JFileChooser class to pop up an Open and Save dialog box.

This will give the end-user the freedom to select any file for reading and writing.

I found below two articles with some example on how to use the class. Please refer them for more information.

https://www.codejava.net/java-se/swing/show-save-file-dialog-using-jfilechooser

How to "Open" and "Save" using java

Thanks.

hel
  • 453
  • 4
  • 12
  • this is what i want to do. the user selects the path. saves it. it writes that path to the file. works fine, but when the program restarts id have to do that every time. because to read from a file(where the path is stored) the program needs a path to look for... – Valasco Dec 10 '19 at 05:35
  • According to your explanation what I understand is, this "path" to the data file is always something important to the program but not the end-user. In that case, you can simply specify a file name in the program code as I have mentioned above, then that file will be created in your program folder where the binaries exist. This will work the same way when you package the program into a JAR file and install in another computer because the path will always be relative and not absolute. Thanks. – hel Dec 10 '19 at 06:12