简体   繁体   中英

Specifying file location for PrintWriter class (Java) and automatically appending .txt

so let's say I ask the user to specify what he wants to call a new file

System.out.println("What do you want to call the file?");

String outputFile = keyboard.nextLine();

now to write the file I would do:

PrintWriter outputFile = new PrintWriter(fileName);

My question are:

  1. I know by default it saves to the local folder. How do I make it so that it will save it to the users desktop?

  2. How do I automatically append .txt to his given file name so he doesn't have to do it?

  1. You have to know the user home. It can vary with the OS (and the user can sometimes define its own), so the best way to be sure is to ask directly the user. You could also keep a list of "default desktop paths".
  2. if(!fileName.endsWith(".txt")) fileName = fileName+".txt";

Resources:

If you're going to ask the user where to put the file, you should probably start with the directory that is given by the system property "user.home", ie call System.getProperty("user.home");
Then you could show a list of directories and ask the user to choose one, drilling down until the user is at the directory he wants to use. On Windows machines, the "Desktop" directory is in fact immediately under the user's home directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM