java rename file extension

Let’s learn java rename file extension.

java rename file extension

Now let’s learn to rename file extension. Here’s the java program.

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RenameFileExtension 
{
   public static boolean renameExtension(String strSource, String strNewExtension)
   {
      String target;
      String strCurrent = findExtension(strSource);
      if(strCurrent.equals(""))
      {
         target = strSource + "." + strNewExtension;
      }
      else 
      {
         target = strSource.replaceFirst(Pattern.quote("." + strCurrent) + "$",Matcher.quoteReplacement("." + strNewExtension));
      }
      return new File(strSource).renameTo(new File(target));
   }
   public static String findExtension(String strFile) 
   {
      String strExtension = "";
      int a = strFile.lastIndexOf('.');
      if(a > 0 &&  a < strFile.length() - 1) 
      {
         strExtension = strFile.substring(a + 1);
      }
      return strExtension;
   }
   public static void main(String[] args) throws IOException 
   {
      System.out.println(RenameFileExtension.renameExtension("A:\\java.txt", "pdf"));
   }
}


Output:

true


Also read – inheritance in java