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);
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...)
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.
Joined: Jun 09, 2003
This might be the easiest way, if you have java 1.4+ (but you will lose subdirectories)
File filename = new File(stdin.readLine().replaceAll("\\\\|\\/",""));