简体   繁体   English

使用正则表达式检查文件扩展名

[英]checking file extension with regular expression

I am writing a program that opens a file and loads all the file contents into a JTextArea. 我正在编写一个程序来打开文件,并将所有文件内容加载到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. 我要接受的格式包括:.js .php .html .asmx .htm .css基本上是Web浏览器中可读的任何格式。

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 最合适的方法是FileNameExtensionFilter

Example (from the FileNameExtensionFilter API ): 示例(来自FileNameExtensionFilter API ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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