简体   繁体   中英

checking file extension with regular expression

I am writing a program that opens a file and loads all the file contents into a JTextArea. I want to restrict users from being able to open different file formats. The formats i want to accept include: .js .php .html .asmx .htm .css basically any format readable in a web browser.

What is the best way to do this?

Should I use a regular expression to check if the file's name matches my criteria or is there a simpler solution?

Here is kind of what I had in mind:

String fileExtensions = "(.js|.php|.html|.asmx|.htm|.css)$"; // $ end of line regex
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);

if (returnValue == JFileChooser.APPROVE_OPTION) {
    File file = fileChooser.getSelectedFile();
    String fileName = file.toString();
    Pattern pattern = Pattern.compile(fileExtensions);
    Matcher matcher = pattern.matcher(fileName);
    if (matcher.find()) {
        openAndReadFile(); // opens the file and outputs contents
    } else {
        // prompt the user to open a different file
    }
} else {
    // do nothing because cancel was pressed
}

Any suggestions?

Do you have to use regex? The most appropriate way to do this would be a FileNameExtensionFilter

Example (from the FileNameExtensionFilter API ):

FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
JFileChooser fileChooser = ...;
fileChooser.addChoosableFileFilter(filter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM