Rename a file extension

From CodeCodex

Revision as of 17:17, 27 August 2009 by Techmind (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Implementations

Java

<highlightsyntax language="java122"> 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;

} </highlightsyntax>