how to change file name without changing extension using java code example

Example: java rename file extension

// java rename file extension
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"));
   }
}

Tags:

Java Example