how to rename file extension in java code example

Example 1: How to rename file in java

// rename file in java example
import java.io.*;
public class RenameFile
{
   public static void main(String[] args) throws IOException
   {
      File oldFile = new File("D:\\Project\\flower.txt");
      File newFile = new File("D:\\Project\\flowerbrackets.txt");
      if(oldFile.renameTo(newFile))
      {
         System.out.println("Rename successful");
      }
      else
      {
         System.out.println("Rename failed");
      }
   }
}

Example 2: 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