Java Program to strip a filename of its extension after the last dot


The method removeExtension() is used to strip a filename of its extension after the last dot. This method requires a single parameter i.e. the file name and it returns the file name without its extension.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static String removeExtension(String fname) {
      int pos = fname.lastIndexOf('.');
      if(pos > -1)
         return fname.substring(0, pos);
      else
         return fname;
   }
   public static void main(String[] args) {
      System.out.println(removeExtension("c:\JavaProgram\demo1.txt"));
   }
}

The output of the above program is as follows −

Output

c:\JavaProgram\demo1

Now let us understand the above program.

The method removeExtension() is used to strip a filename of its extension after the last dot. A code snippet that demonstrates this is given as follows −

public static String removeExtension(String fname) {
   int pos = fname.lastIndexOf('.');
   if(pos > -1)
      return fname.substring(0, pos);
   else
      return fname;
}

The method main() prints the file name without the extension that was returned by the method removeExtension(). A code snippet that demonstrates this is given as follows −

public static void main(String[] args) {
   System.out.println(removeExtension("c:\JavaProgram\demo1.txt"));
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements