Rename a file extension

From CodeCodex

Implementations[edit]

Erlang[edit]

rename_file_extention(Source, Extension) ->
    Rootname = filename:rootname(Source),
    Destination = if  Extension =:= "" -> Rootname;
                      true             -> Rootname ++ "." ++ Extension
                  end,
    file:rename(Source, Destination).

Java[edit]

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;
}

Ruby[edit]

def rename_file_extension(source, extension)
  dirname  = File.dirname(source)
  basename = File.basename(source, ".*")
  extname  = File.extname(source)
  if extname == ""
    if basename[0,1]=="."
      target = dirname + "/." + extension
    else
      target = source + "." + extension
    end
  else
    target = dirname + "/" + basename + "." + extension
  end
  File.rename(source, target)
  target
end