Rename a file extension

From CodeCodex

Revision as of 11:05, 4 January 2011 by 211.2.129.92 (Talk)

Implementations

Erlang

rename_file_extention(Source, Extension) ->
    Dirname  = filename:dirname(Source),
    Extname  = filename:extension(Source),
    Basename = filename:basename(Source, Extname),
    Filename = if  Extension =:= "" -> Basename;
                   true             -> Basename ++ "." ++ Extension
               end,
    Destination = if  Dirname =:= "." -> Filename;
                      Dirname =:= "/" -> Dirname ++ Filename;
                      true            -> Dirname ++ "/" ++ Filename
                  end,
    file:rename(Source, Destination).

Java

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

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