• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating file or folder but using user input for name problem  RSS feed

 
Conn Osullivan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi new to java, and java ranch,

File dir = new File("file"); //creates folder named file
File dir1 = new File("file.txt"); //creates file

but I want to take in a file name from user e.g.

BufferedReader br = new BufferedReader(is);
String filename = br.readLine( );
File dir = new File(filename + ".txt");

its expecting a string literal is there a way round it to take a string???
 
Jacob Anawalt
Ranch Hand
Posts: 64
Linux Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to Java and the ranch.

The File constructor is not expecting a string literal. When you did new File("file"), "file" was converted into a String. The File constructor taking a String is File(String pathname).

Have you looked at filename + ".txt" to see if it is what you expect?

What is the error that makes you think File is expecting a string literal?
 
Conn Osullivan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I try

BufferedReader br = new BufferedReader(is);
String filename = br.readLine( );
File dir = new File(filename);

or

BufferedReader br1 = new BufferedReader(is);
String fileName = br1.readLine( );
File file = new File(fileName + ".txt");

nothing created but


File dir = new File("file"); //creates folder named file
File dir1 = new File("file.txt"); //creates file ???

 
Jacob Anawalt
Ranch Hand
Posts: 64
Linux Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should look at filename + ".txt" to see that it is what you expected. Maybe you are creating a file named .txt.

If you don't have a debugger to step through the code with, try printing:



Maybe that's not the problem though and it's somewhere else because you're mis-understanding when the file is really created. For example File dir = new File("file") doesn't create a file or a directory. It creates a new File instance by converting the given pathname String into an abstract pathname. If you then do dir.mkdir(), a directory is created. If you instead did dir.createNewFile() it would have created an empty file named file, not a directory, as long as a file or directory by that name did not already exist.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

The File class is called “legacy” by the Java Tutorials. Go through that section and it should give you the answers.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!