0 votes
44 views
in Java by
How to get the file extension of a file in Java ?

1 Answer

0 votes
by (2.8k points)

To get file extension in java by using lastIndexOf and substring method. For more see the following running code for getting file extension:-

public static String getFileExtension(String fileName) {

    int lastIndexOf = fileName.lastIndexOf(".");

    if (lastIndexOf == -1) {

        return ""; // empty extension

    }

    return fileName.substring(lastIndexOf);

}

public static String getFileExtension(File file) {

    String name = file.getName();

    int lastIndexOf = name.lastIndexOf(".");

    if (lastIndexOf == -1) {

        return ""; // empty extension

    }

    return name.substring(lastIndexOf);

}

File Name:- abc.jpg

Output:-  .jpg

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...