Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check for invalid file name

 
John Powell
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a loop that requires the user to enter a valid filename to continue. I currently have it set up to loop if the user hits enter without typing anything in (null). In Windows you cannot enter a filename with the forbidden characters \/:*?"<>|. Is there an easy way to check for invalid filenames or do I have to add each individual character to my validation checks (e.g. filename.equals("")||filename.equals("?")||...etc);

 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, John -

Have you looked into regular expressions (regex)? A regular expression can test for the presence (or absence) of any one or more of a list of characters.

Even if you don't use regex, you can store the invalid characters in a char array, then loop through the array testing to make sure indexOf the test character is not greater than zero.
[ November 16, 2004: Message edited by: Jeff Bosch ]
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
something like this might be all you need to do

 
John Powell
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff, Michael, thanks for the info.

Michael,

The code you posted works great for most of the invalid characters but it doesn't detect the slashes ("/" and "\"). If I enter either slash for the filename it exits out of the loop even though it's a invalid file name.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This might be the easiest way, if you have java 1.4+
(but you will lose subdirectories)

File filename = new File(stdin.readLine().replaceAll("\\\\|\\/",""));
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic