• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Check for invalid file name

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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);

 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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("\\\\|\\/",""));
 
reply
    Bookmark Topic Watch Topic
  • New Topic