Preface
In Java development, especially in web applications or file processing scenarios, obtaining file suffix names is a high-frequency requirement. Whether it is file upload verification, type filtering, format verification, or logging, the correct extraction of the suffix name is the core basis.
1. Basic method: lastIndexOf + substring
definition: By positioning the last one.
position, intercept the suffix name.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); if (originalFilename == null || ()) { return ""; } int dotIndex = ('.'); if (dotIndex == -1 || dotIndex == () - 1) { return ""; } return (dotIndex + 1).toLowerCase(); }
Execution effect:
- file name
report_v2.
→ Returnxlsx
- file name
image.
→ Return empty string - file name
.gitignore
→ Returngitignore
2. String segmentation: split method
definition:pass.
Split the file name and take the last element.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); if (originalFilename == null) { return ""; } String[] parts = ("\\."); return > 1 ? parts[ - 1].toLowerCase() : ""; }
Execution effect:
- file name
archive.v1.7z
→ Return7z
- file name
file
→ Return empty string
3. Regular expressions
definition: match the last one by regular.
The string after that.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); if (originalFilename == null) { return ""; } Pattern pattern = ("\\.(\\w+)$"); Matcher matcher = (originalFilename); return () ? (1).toLowerCase() : ""; }
Execution effect:
- file name
→ Return
pdf
- file name
→ Return
gz
4. FilenameUtils of Apache Commons IO
definition: Tool class that uses Apache Commons IO.
Enter the ginseng:MultipartFile file
rely:
<dependency> <groupId></groupId> <artifactId>commons-io</artifactId> <version>9.0.0</version> </dependency>
Code Example:
import ; public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); return (originalFilename).toLowerCase(); }
Execution effect:
- file name
→ Return
txt
- file name
file.
→ Return empty string
5. StringUtils of Spring Framework
definition: Use Spring's tool class.
Enter the ginseng:MultipartFile file
rely:
<dependency> <groupId></groupId> <artifactId>spring-core</artifactId> <version>6.0.10</version> </dependency>
Code Example:
import ; public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); return (originalFilename); }
Execution effect:
- file name
→ Return
jpg
- The return value is
null
Pay attention to null pointers (such asfile
No extension).
6. Use the File class
definition: Through structureFile
Object extract file name.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
import ; public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); if (originalFilename == null) { return ""; } File tempFile = new File(originalFilename); String name = (); int dotIndex = ('.'); return (dotIndex > 0 && dotIndex < () - 1) ? (dotIndex + 1).toLowerCase() : ""; }
Execution effect:
- file name
→ Return
csv
- file name
config.
→ Return empty string
7. Java NIO's Paths class
definition:passPacket processing path.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
import ; import ; public static String getExtension(MultipartFile file) { if (file == null) { return ""; } String originalFilename = (); if (originalFilename == null) { return ""; } Path path = (originalFilename); String name = ().toString(); return (('.') + 1).toLowerCase(); }
Execution effect:
- file name
→ Return
pdf
- Good cross-platform compatibility (such as path
/home/
→ Extracttxt
)。
8. Combined with MIME type verification
definition:pass()
Verify the suffix.
Enter the ginseng:MultipartFile file
rely:none
Code Example:
public static boolean validateFile(MultipartFile file) { String ext = getExtension(file); // Use any of the above methods String contentType = (); return ("jpg") && ("image/jpeg"); }
Execution effect:
- file name
And MIME is
image/jpeg
→ Returntrue
- file name
But MIME is
image/jpeg
→ Returnfalse
9. Custom enumeration filtering
definition: The allowed suffix is limited by enumeration.
Enter the ginseng:MultipartFile file
Code Example:
enum FileType { PNG, JPG, JPEG, GIF; public static boolean isValid(String ext) { for (FileType type : ()) { if (().equalsIgnoreCase(ext)) { return true; } } return false; } } public static String getValidExtension(MultipartFile file) { String ext = getExtension(file); return (ext) ? ext : ""; }
Execution effect:
- file name
→ Return
jpg
- file name
→ Return empty string
10. Use Lombok's @Cleanup to simplify the code
definition: Reduce resource management code with Lombok.
Enter the ginseng:MultipartFile file
rely:
<dependency> <groupId></groupId> <artifactId>lombok</artifactId> <version>1.18.28</version> <scope>provided</scope> </dependency>
Code Example:
import ; public static String getExtension(MultipartFile file) { if (file == null) { return ""; } @Cleanup InputStream inputStream = (); // Other logic (such as reading file content) return "ext"; // Example return value}
Execution effect:
- Automatically close
inputStream
, no need to manually manage resources.
Method comparison table
method | rely | Boundary processing | performance | Applicable scenarios |
---|---|---|---|---|
lastIndexOf + substring
|
none | Improved (needed to be manually processed) | high | Simple scenario, no dependency requirements |
split |
none | Simple (need to judge the length of the array) | middle | Quickly implemented without special needs |
Regular expressions | none | Flexible (regularly scalable) | middle | When complex matching is required |
Apache Commons IO | commons-io |
Automatic processing | high | Requires multiple file operation functions |
Spring StringUtils
|
spring-core |
Automatic processing | high | Use within the Spring ecosystem |
File kind |
none | Base | middle | When path processing is required |
Java NIO Paths
|
none | Base | middle | Modern API, cross-platform requirements |
MIME type verification | none | Depend on MIME type | high | Security verification scenario |
Best Practice Recommendations
-
Dependency selection:
-
Zero dependency scenario: Priority
lastIndexOf
orsplit
。 -
Complex requirements: Using Apache Commons IO or Spring
StringUtils
。
-
Zero dependency scenario: Priority
-
Boundary situation handling:
- File name with
.
The beginning (such as.gitignore
): Return the suffixgitignore
。 - File name has no extension (such as
file
): Returns an empty string. - File name with
.
Ending (such asfile.
): Returns an empty string.
- File name with
-
Suffix is uniform lowercase:
- use
toLowerCase()
Avoid case sensitive issues (such asJPG
→jpg
)。
- use
-
Security Verification:
- Combining MIME type and suffix double verification (such as
image/jpeg
andjpg
)。
- Combining MIME type and suffix double verification (such as
Summarize
ForMultipartFile
Get the suffix name of , and select it in combination with the project requirements:
-
Basic scene:recommend
lastIndexOf
or Apache Commons IO. -
Spring Ecosystem: Use directly
。
- Safety-sensitive scenarios: Combined with MIME type verification.
The above is the detailed content of the method of obtaining file suffix names in Java. For more information about obtaining file suffix names in Java, please pay attention to my other related articles!