Get filename without extension using Java

 Posted On  | Yashwant Chavan 

This file utility method helps you to remove the file extension from file name. Here I am using simple regular expression which will remove the last dot followed by one or more characters of file extension.

Get File name without extension

package com.technicalkeeda.app;

import java.io.File;

public class FileNameWithoutExtensionExample {
    public static void main(String[] args) {
        String fileName = getFileNameWithoutExtension(new File("C:\\article\\mongodb-json.zip"));
        System.out.println("File Name :- " + fileName);
        fileName = getFileNameWithoutExtension(new File("C:\\article\\eclipse.png"));
        System.out.println("File Name :- " + fileName);
    }

    private static String getFileNameWithoutExtension(File file) {
        String fileName = "";

        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                fileName = name.replaceFirst("[.][^.]+$", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            fileName = "";
        }

        return fileName;

    }

}

Output

Let us compile and execute the above program.

File Name :- mongodb-json
File Name :- eclipse


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0313 seconds.