Real'sHowTo AddThis Feed Button
Custom Search

Rename a file extensionTag(s): IO


The first version
public static boolean renameFileExtension
     (String source, String newExtension)
{
   String target;
   String currentExtension = getFileExtension(source);

   if (currentExtension.equals("")){
      target = source + "." + newExtension;
   }
   else {
      target = source.replaceAll("." + currentExtension, newExtension);
   }
   return new File(source).renameTo(new File(target));
 }

 public static String getFileExtension(String f) {
   String ext = "";
   int i = f.lastIndexOf('.');
   if (i > 0 &&  i < f.length() - 1) {
      ext = f.substring(i + 1).toLowerCase();
   }
   return ext;
}

Comments from R.Millington (thanks to him!)

This code very very seriously flawed (the first version -ed.).

This is fixed by changing the replaceAll() line to

target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));

A revised version

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {

  public static boolean renameFileExtension
  (String source, String newExtension)
  {
    String target;
    String currentExtension = getFileExtension(source);

    if (currentExtension.equals("")){
      target = source + "." + newExtension;
    }
    else {
      target = source.replaceFirst(Pattern.quote("." +
          currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));

    }
    return new File(source).renameTo(new File(target));
  }

  public static String getFileExtension(String f) {
    String ext = "";
    int i = f.lastIndexOf('.');
    if (i > 0 &&  i < f.length() - 1) {
      ext = f.substring(i + 1);
    }
    return ext;
  }

  public static void main(String args[]) throws Exception {
    System.out.println(
         FileUtils.renameFileExtension("C:/temp/capture.pdf", "pdfa")
         );
  }
}
To simply remove an extension, see this HowTo
blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2013
[ home ]