This is not a problem, using the framework of the original method, or the file class GetPath () method, take out to determine the file path, or the GetName () method to remove the file path, as a string string assumed to be filename, With this filename, the endswith ("TXT") method, the Boolean value can be used to determine whether the TXT file. There was nothing to say, but what would happen? For example, to determine whether it is a picture file, especially some upload system, your judgment conditions will be written in the following form:
if (Filename.endswith (". jpg") | | filename.endswith (". jpeg") | | filename.endswith (". bmp") | | Filename.endswith (". gif") | | filename.endswith (". png")) {}
In the case of allowing more file types, very ugly, at this time can take advantage of the IndexOf method and Java variable length parameters can be a perfect solution to this problem, specifically, "Java" JDK1.5 after the new type of generic parameter transfer method Object...args " (Click to open the link) Here is no longer to repeat.
For example, the following program, determine whether the file is a. txt,.png,gif,.bmp, and the f:\\a.jsp this path to test, the code is as follows:
Package Isvalid;public class Validtest {public static Boolean isValid (String ContentType, String ... allowtypes) {if (null = = ContentType | | "". Equals (ContentType)) {return false;} for (String type:allowtypes) {if (Contenttype.indexof (Type) >-1) {return true;}} return false;} public static void Main (string[] args) {string[] allowtypes = new string[] {". txt", ". png", "GIF", ". bmp"}; Boolean canuploaded = IsValid ("f:\\a.jsp", Allowtypes), if (canuploaded) {System.out.println ("The file is. Txt,.png,gif,". BMP one, allow upload! ");} else {System.out.println ("The file is not one of the. txt,.png,.gif,.bmp, no uploads! ");}}}
The results of the operation are as follows:
This avoids having to write too many things in the IF.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Java" to determine the suffix name of the file