Java get Filename without Extension

In this section, you will learn how to obtain the filename without extension. For this, the file name or the directory name is being provided.

Java get Filename without Extension

Java get Filename without Extension

     

In this section, you will learn how to obtain the filename without extension. For this, the file name or the directory name is being provided.

file.getName()- This method returns the file name.

lastIndexOf()-This method returns the index within this string.

file.length()-This method returns the length of the file.

substring(0, index)-  This method returns a new string that is a substring of this string.

Here is the code of GetFilenameWithoutExtension.java

import java.io.File;
public class GetFilenameWithoutExtension{

public static String getFileNameWithoutExtension() {
  String fileName="C:\\anu\\My\\Hello.txt";
  File file = new File(fileName);
  
  int index = file.getName().lastIndexOf('.');
      if (index>0&& index <= file.getName().length() - 2 ) {
      System.out.println("Filename without Extension: "+file.getName().substring(0, index));
      }  
    return "";
    }
public static void main(String []args){
GetFilenameWithoutExtension example=new GetFilenameWithoutExtension();
example.getFileNameWithoutExtension();
}
}

Output will be displayed as:

Download Source Code