Java 17 Recipes


-15. Determining Whether a File Suffix Matches


Download 3.2 Mb.
Pdf ko'rish
bet63/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   59   60   61   62   63   64   65   66   ...   245
Bog'liq
Java 17 Recipes

3-15. Determining Whether a File Suffix Matches 
a Given String
 Problem
You are reading a file from the server, and you need to determine what type of file it is to 
read it properly.
Chapter 3 StringS


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


104

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   59   60   61   62   63   64   65   66   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling