Difference between revisions of "Rename a file extension"

From CodeCodex

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

Latest revision as of 17:23, 17 January 2011

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