-4

I got questions about creating files in Java.

I searched for some time and couldn't find way to save file with name defined by user (like you can in almost any other program).

Everywhere I look file name is defined in new File("something.sth") or things similar to that.

What I want to do is to write file with name defined by user and extension defined by me.

Something like: file1.aaa; file2.aaa;

etc.

Please help with comment or tutorial or part of code.

Thank you in advance :)

Allspark
  • 5
  • 2
  • 4
    Do you know how to get input from a user? Once they type in a string it is very simple to concatenate that with a string that you define (your extension) and use the newly created string as the filename. – takendarkk Nov 14 '14 at 23:20
  • Then change new File("something.sth") to File(yourInputFromUser) – Salih Erikci Nov 14 '14 at 23:21
  • `new File("~", new Scanner(System.in).readLine())` –  Nov 14 '14 at 23:22
  • This appears to be a request for a basic Java tutorial... Stack Overflow isn't really here for that sort of thing. If you've tried something and have specific issues you should say so, otherwise you will have more luck searching for tutorials or asking on other forums. – Rook Nov 15 '14 at 12:46

1 Answers1

0

You need a method to get the name from the user. I presume you have that. And you need a folder within which to save the files (unless you want the user to specify folder as well).

When users enter file names, they might type characters that are not allowed in file names. You must scan the characters and sanitize what they type, otherwise the file creation will fail.

File   folder           = new File("/put/the/desired/path/here/");
String fileNameFromUser = methodToGetFilename();
       fileNameFromUser = cleanBadCharacters(fileNameFromUser);
File   theFile          = new File(folder, fileNameFromUser + ".aaa");

now you can open, read, or write, the file specified by the user. Note that the variable folder is defined by you, either a string path, or another File variable.

AgilePro
  • 5,588
  • 4
  • 33
  • 56