Reputation: 13922
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?
Upvotes: 0
Views: 1963
Reputation: 3859
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);
Upvotes: 3