Java Reference
In-Depth Information
3-10. Determining Whether a File Name
Ends with a Given String
Problem
You are reading a file from the server and you need to determine what type of file it is
in order to read it properly.
Solution
Determine the suffix of the file by using the endsWith() method on a given file
name. In the following example, assume that the variable filename contains the
name of a given file, and the code is using the endsWith() method to determine
whether filename ends with a particular string.:
if(filename.endsWith(".txt")){
System.out.println("Text file");
} else if (filename.endsWith(".doc")){
System.out.println("Document file");
} else if (filename.endsWith(".xls")){
System.out.println("Excel file");
} else if (filename.endsWith(".java")){
System.out.println("Java source file");
} else {
System.out.println("Other type of file");
}
Given that a file name and its suffix are included in the filename variable, this
block of code will read its suffix and determine what type of file the given variable rep-
resents.
How It Works
As mentioned previously, the String object contains many helper methods that can
be used to perform tasks. The String object's endsWith() method accepts a char-
Search WWH ::




Custom Search