我正在编写一个打开文件并将所有文件内容加载到 JTextArea 的程序。我想限制用户打开不同的文件格式。我想接受的格式包括: .js .php .html .asmx .htm .css 基本上是在网络浏览器中可读的任何格式。
做这个的最好方式是什么?
我应该使用正则表达式来检查文件名是否符合我的条件,还是有更简单的解决方案?
这是我的想法:
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
}
有什么建议么?