SoFunction
Updated on 2025-05-21

Summary of the method of obtaining file suffix name in Java

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 ginsengMultipartFile 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 namereport_v2.→ Returnxlsx
  • file nameimage.→ 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 ginsengMultipartFile 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 namearchive.v1.7z→ Return7z
  • file namefile→ Return empty string

3. Regular expressions

definition: match the last one by regular.The string after that.

Enter the ginsengMultipartFile 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→ Returnpdf
  • file name→ Returngz

4. FilenameUtils of Apache Commons IO

definition: Tool class that uses Apache Commons IO.

Enter the ginsengMultipartFile 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→ Returntxt
  • file namefile.→ Return empty string

5. StringUtils of Spring Framework

definition: Use Spring's tool class.

Enter the ginsengMultipartFile 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→ Returnjpg
  • The return value isnullPay attention to null pointers (such asfileNo extension).

6. Use the File class

definition: Through structureFileObject extract file name.

Enter the ginsengMultipartFile 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→ Returncsv
  • file nameconfig.→ Return empty string

7. Java NIO's Paths class

definition:passPacket processing path.

Enter the ginsengMultipartFile 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→ Returnpdf
  • Good cross-platform compatibility (such as path/home/→ Extracttxt)。

8. Combined with MIME type verification

definition:pass()Verify the suffix.

Enter the ginsengMultipartFile 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") &amp;&amp; ("image/jpeg");
}

Execution effect

  • file nameAnd MIME isimage/jpeg→ Returntrue
  • file nameBut MIME isimage/jpeg→ Returnfalse

9. Custom enumeration filtering

definition: The allowed suffix is ​​limited by enumeration.

Enter the ginsengMultipartFile 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→ Returnjpg
  • file name→ Return empty string

10. Use Lombok's @Cleanup to simplify the code

definition: Reduce resource management code with Lombok.

Enter the ginsengMultipartFile 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 closeinputStream, 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
Filekind 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

  1. Dependency selection

    • Zero dependency scenario: PrioritylastIndexOforsplit
    • Complex requirements: Using Apache Commons IO or SpringStringUtils
  2. Boundary situation handling

    • File name with.The beginning (such as.gitignore): Return the suffixgitignore
    • File name has no extension (such asfile): Returns an empty string.
    • File name with.Ending (such asfile.): Returns an empty string.
  3. Suffix is ​​uniform lowercase

    • usetoLowerCase()Avoid case sensitive issues (such asJPG → jpg)。
  4. Security Verification

    • Combining MIME type and suffix double verification (such asimage/jpegandjpg)。

Summarize

ForMultipartFileGet the suffix name of  , and select it in combination with the project requirements:

  • Basic scene:recommendlastIndexOfor 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!