开发者

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 w开发者_如何转开发ould 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:

  • String.endsWith()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜