Difference between revisions of "Rename a file extension"

From CodeCodex

(Erlang)
Line 1: Line 1:
 
==Implementations==  
 
==Implementations==  
===Java===  
+
===Erlang===
 +
<pre>
 +
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).
 +
</pre>
 +
 
 +
===Java===
 
<pre class="java">
 
<pre class="java">
 
public static boolean renameFileExtension
 
public static boolean renameFileExtension
Line 47: Line 63:
 
</pre>
 
</pre>
  
 +
[[Category:Erlang]]
 
[[Category:Java]]
 
[[Category:Java]]
 
[[Category:Ruby]]
 
[[Category:Ruby]]
 
[[Category:I/O]]
 
[[Category:I/O]]

Revision as of 11:05, 4 January 2011

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