Remove Extension of File Java Code

Remove Extension of a File


The operation is a simple one and is crucial in case of file handling. Though mostly we need to remove the file extension before processing the file, there may be other requirements that ask for this requirement.

Anyhow the Java Code is provided below:-

//////////////////////////////

package developer;

import java.util.Scanner;

public class RemoveFileExtension {

public static void main(String[] args) {

String fileRemExt = null;

System.out.println("Enter a valid file name whose extension is to be removed:");

Scanner rem = new Scanner(System.in);

if(rem.hasNext())
{
fileRemExt = removeFileExtension(rem.next());
}

if(null != fileRemExt)
{
System.out.println("The file name without extension is: "+fileRemExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//remove the file extension of the file entered
public static String removeFileExtension(String fileName)
{ 
if(null != fileName && fileName.contains("."))
{
return fileName.substring(0, fileName.lastIndexOf("."));
}
return null;
}

}
////////////////////////////////////

Once this code is executed, the output is something like:-

////////////////////////////////////
Output

Enter a valid file name whose extension is to be removed:
test.java
The file name without extension is: test
////////////////////////////////////