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

StackOverflow https://stackoverflow.com/questions/3972601

  •  09-10-2019
  •  | 
  •  

سؤال

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", i.e. 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top