aspose file tools*
The moose likes Beginning Java and the fly likes Check for invalid file name Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Check for invalid file name" Watch "Check for invalid file name" New topic
Author

Check for invalid file name

John Powell
Greenhorn

Joined: Nov 13, 2004
Posts: 11
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

Joined: Jul 30, 2003
Posts: 805
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 ]

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
something like this might be all you need to do

John Powell
Greenhorn

Joined: Nov 13, 2004
Posts: 11
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

Joined: Jun 09, 2003
Posts: 4632
This might be the easiest way, if you have java 1.4+
(but you will lose subdirectories)

File filename = new File(stdin.readLine().replaceAll("\\\\|\\/",""));
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Check for invalid file name