Visualizzazione post con etichetta file. Mostra tutti i post
Visualizzazione post con etichetta file. Mostra tutti i post

venerdì 14 gennaio 2011

Ruby: flatten directory [ENG]

We've organized files in subdirectories according to tags and according to creation date. What if you would like to flatten a tree, moving all files from the sub-directories into a single directory?

"Move all the files from the tree starting at source_dir"
"into dest_dir out of the tree"
def flatten(source_dir, dest_dir)
 Dir.foreach(source_dir) do |filename|
    # exclude current dir and parent dir
    if (!filename.eql?(".") and !filename.eql?("..")) 
     if File.directory?(filename) # subdirectory
       flatten(filename, dest_dir) # recursively flatten subdir
     else #file
       dirname = File.dirname(filename)
       filenameonly = filename[(dirname.length-1)..-1]
       old_name = source_dir + "/" + filename
       new_name = dest_dir + "/" + filenameonly
       puts("moving '#{old_name}' to '#{new_name}'")
       File.rename(old_name, new_name) 
     end
    end
  end
end

# read line parameters

source_dir = ARGV.shift
# default source dir is current dir
if (source_dir == nil) 
  source_dir = "."
end

dest_dir = ARGV.shift
# default destination dir current dir
if (dest_dir == nil)
  dest_dir = "."
end 

flatten(source_dir, dest_dir)

venerdì 6 novembre 2009

Java: reading & writing files [ENG]

Since I can NEVER remember... here's the (very) quick and dirty code to read & write from text files.

private String readFile(String fileName)
  {
    if (fileName==null || "".equals(fileName))
    {
      return null;
    }
    try
    {
      FileReader reader = new FileReader(fileName);
      int next = -1;
      StringBuffer s = new StringBuffer();
      do 
      {
          next = reader.read();  
          if (next != -1) 
          {
              s.append((char)next); 
          }

      } while (next != -1);

      reader.close();  
      return s.toString();
    }
    catch (Exception e)
    {
      log(e.getMessage(), Project.MSG_ERR);
      throw new BuildException(e);
    }
  }
// --------------------------------------------------------

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) 
{
   // process the line.
}
br.close();  

// --------------------------------------------------------
  private void writeFile(String content, String fileName)
  {
    try
    {
      FileWriter writer = new FileWriter(fileName, false);
      writer.write(content);
      writer.close();
    }
    catch (Exception e)
    {
      log(e.getMessage(), Project.MSG_ERR);
      throw new BuildException(e);
    }
  }