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

Java 8Object Oriented ProgrammingProgramming

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"));
}
raja
Published on 25-Feb-2019 12:06:02
Advertisements