Answers for "how to change file name without changing extension using java"

1

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"));
   }
}
Posted by: Guest on February-19-2021

Code answers related to "how to change file name without changing extension using java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language