0

I want to be able to open a text file with some basic instruction from within a program in Java, What I currently have to open the file:

Desktop desktop = Desktop.getDesktop();
File file = new File(/* File Path, this is what I am concerned with. */);
if(file.exists())
try {
     desktop.open(file);
} catch (IOException e) {e.printStackTrace();}

This works fine, what I have been using for the path is:

"/Users/Box/Documents/text.txt"

The reason I have a problem is because I want to send my program to a friend so that he can try it out. The current solution I have is to have a text field that the user can input their username into and then the path is:

"/Users/" + username + "/Documents/text.txt" (username being the username that is inputed into the text field)

Where else could I store the file or what else could I use for a path? Is there a way to find the user automatically? Should I store the file in a folder made in the root?

Box
  • 1
  • 3

1 Answers1

1

If you like to use a fixed path under the user folder, you can get the username via

String username = System.getProperty("user.name");

Alternatively you can use a path relative to the location of the program, for example Paths.get("").toAbsolutePath(), see Getting the Current Working Directory in Java

Christian Fries
  • 16,175
  • 10
  • 56
  • 67