Saturday, August 22, 2009

Remove Extension of File Java Code

Hello friends, welcome once again at Java Code Online. The topic of the day is the Java code that helps in removing the extension of a file name that is entered by the user.

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
////////////////////////////////////

I hope the article was helpful to most of you. In case you liked the article then do leave a comment at Java Code Online.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.