103
Solution
Determine the suffix of the file by using the endsWith() method on a given file name. In
the following example, assume that the filename variable contains the name of a given
file. The code uses the endsWith() method to determine whether
the filename variable
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 reads its suffix and determines what type of file the given variable represents.
How It Works
As
mentioned, the String object contains many helper methods that can perform tasks.
The String object’s endsWith() method accepts a character sequence and returns a
Boolean value representing whether the original string ends with the given sequence.
In the case
of the solution to this recipe, the endsWith() method is used in an if block.
A series of file suffixes are passed to the endsWith() method to determine what type of
file is represented by the filename variable. If any of
the file name suffixes match, a line
prints, stating which type of file it is.
Chapter 3 StringS