Java I/O How to - Validate a file name on Windows








Question

We would like to know how to validate a file name on Windows.

Answer

import java.io.File;
import java.io.IOException;
//from   w w  w. ja  va2s  .c  o m
public class Main {
  public static boolean isFilenameValid(String file) {
    File f = new File(file);
    try {
       f.getCanonicalPath();
       return true;
    }
    catch (IOException e) {
       return false;
    }
  }

  public static void main(String args[]) throws Exception {
    // true
    System.out.println(FileUtils.isFilenameValid("asdf.txt"));

    //false
    System.out.println(FileUtils.isFilenameValid("test.T*T"));
    }
  }