Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 41 total

Rename all *.gif files in a directory (prefix)

// My mind always seems to draw a blank when I want to do this sort of thing, so here's a concise little self-reminder

   1  
   2  for file in $(echo *.gif); do mv ${file} prefix.${file}; done

basename & dirname in Perl

These two Perl functions implement approximations of the UNIX utilities `basename` and `dirname`, though basename() automatically strips off the last extension no matter what.
   1  sub basename($) {
   2   my $file = shift;
   3   $file =~ s!^(?:.*/)?(.+?)(?:\.[^.]*)?$!$1!;
   4   return $file;
   5  }
   6  
   7  sub dirname($) {my $file = shift; $file =~ s!/?[^/]*/*$!!; return $file; }

Image aggregator

This PHP snippet outputs the contents of a table (beginning & ending tags not included) containing all the images from the current directory.
   1  <?PHP
   2   $columns = 3;
   3   $im = glob("*.{gif,jpg,png}", GLOB_BRACE);
   4   $rows = ceil(count($im) / $columns);
   5   for ($i = 0; $i < $rows; $i++) {
   6    echo "\n<TR>";
   7    for ($j = $columns*$i; isset($im[$j]) && $j - $columns*$i < $columns; $j++) {
   8     echo "<TD>$im[$j]<BR><IMG SRC='$im[$j]'></TD>";
   9    }
  10    echo "</TR>";
  11   }
  12  ?>

File extension counter

Produces a count of the frequencies of each file extension in the directories named on the command line
   1  
   2  #!/usr/bin/perl -w
   3  use strict;
   4  my %exten;
   5  foreach (@ARGV) {
   6   /(\.[^.]+)$/ && $exten{$1}++ foreach glob "$_/*.*"
   7  }
   8  print "$_: $exten{$_}\n" foreach sort keys %exten;

Organize photos and other files on an year/month/day folders structures

This script can organize you media colelction in folders by year/month/day.
For jpeg files, looks in exif for the creation date, if that file has that kind of metadadata. For any other files it only checks the creation time.
The script takes 3 option on the command line. A command which may be -m, -c or -f, a source folder and a destination folder.
Using -c will copy the files from souce to destination, -m will move them, - f will also move them, by making first a copy then a delete. -f option may used when -m doesn't work, the most common situation beeing when you want to move the files from one file system to another(e.g. from your ext3 local hard drive to an external fat32 usb harddrive)
After you organize the files, you can find duplicate items using my previous snippet.
This script have been inspired from here
   1  
   2  #!/usr/local/bin/ruby
   3  require 'rubygems'
   4  require 'ftools'
   5  require 'exifr'
   6  
   7  
   8  def process_file(file_path,destination_dir)
   9  	if File.directory?(file_path)
  10  		crt_dir = Dir.new(file_path)
  11  		crt_dir.each do |file_name|
  12  			if file_name != '.' &&  file_name != '..'				
  13  				process_file("#{crt_dir.path}/#{file_name}",destination_dir)		
  14  			end
  15  		end	
  16  	else
  17  			
  18  		if  File.fnmatch('*.jpg',file_path) ||  File.fnmatch('*.jpeg',file_path)
  19  			picture = EXIFR::JPEG.new(file_path)
  20  			if picture != nil && picture.exif != nil
  21  				file_date = picture.date_time		
  22  			else
  23  				f = File.new(file_path)
  24  				file_date = f.mtime
  25  			end							
  26  		end
  27  		if file_date == nil
  28  			f = File.new(file_path)
  29  			file_date = f.mtime	
  30  		end		
  31  		year_dir =  destination_dir + file_date.strftime("%Y")
  32  		month_dir = destination_dir + file_date.strftime("%Y/%m-%b")
  33  		day_dir = destination_dir + file_date.strftime("%Y/%m-%b/%d")
  34  		new_file_name = day_dir + "/" + File.basename(file_path)
  35  		begin
  36  			Dir.mkdir(year_dir) unless File.exists?(year_dir)
  37  			Dir.mkdir(month_dir) unless File.exists?(month_dir)
  38  			Dir.mkdir(day_dir) unless File.exists?(day_dir)
  39  			if ARGV[0 ] =='-m' #move the files
  40  				File.rename(file_path, new_file_name)
  41  			elsif ARGV[0]  =='-c' #copy the files
  42  				File.cp(file_path, new_file_name)	
  43  			elsif ARGV[0]  =='-f' #copy and delete, acts like a move between thw different file systems	
  44  				File.cp(file_path, new_file_name)
  45  				File.delete(file_path)	
  46  			else
  47  				puts "Unknown option #{ARGV[0]}"
  48  				exit	
  49  			end	
  50  		end	
  51  		
  52  	end	
  53  end
  54  
  55  
  56  if ARGV.length != 3
  57  	puts "Three arguments are required to run the script, -c|-m|-f <source_folder_or_file>  <destination_folder>"
  58  	exit
  59  end
  60  
  61  if ARGV[0] !='-c'  && ARGV[0]!='-m' && ARGV[0]!='-f'
  62  	puts "Unknown running option: #{ARGV[0]}"
  63  	exit
  64  end
  65  
  66  if not File.exists?(ARGV[1]) 
  67  	puts "Source file does not exists: #{ARGV[1]}"
  68  	exit
  69  end
  70  
  71  
  72  if not File.directory?(ARGV[2]) 
  73  	puts "Destination file is not a directory #{ARGV[2]}"
  74  	exit
  75  end
  76  
  77  if ARGV[1]==ARGV[2]
  78  	puts "Source and destination must be different"
  79  	exit
  80  end	
  81  	
  82  	
  83  process_file(ARGV[1], ARGV[2])

Directory List with PHP

// description of your code here

This code list all files and subdirectories in a dirctory with links.

   1  
   2  
   3  <html><head><title>ribafs.net - Tutoriais</title></head>
   4  <body bgcolor='#FFFACD'>
   5  <h2 align=center><a href="http://ribafs.net">http://ribafs.net - <?php echo date('d/m/Y H:i:s'); ?></a></h2>
   6  
   7  <?php
   8  $dn = opendir (dirname(__FILE__));
   9  $exclude = array("index.php", ".", "..");
  10  
  11  // adiciona os arquivos ao array $arquivos
  12  while($fn = readdir($dn)) {
  13  	if ($fn == $exclude[0] || $fn == $exclude[1] || $fn == $exclude[2]) continue;
  14  	$arquivos[] = $fn;
  15  }
  16  // ordena o vetor
  17  sort($arquivos);
  18  // exibe os arquivos
  19  
  20  foreach ($arquivos as $arquivo)
  21  
  22  if (is_dir($arquivo)){
  23  	$dir .= "<img src='/imagens/diretorio.png'>&nbsp;<a href='$arquivo'>$arquivo</a><br>";
  24  }else{
  25  	$tamanho = filesize($arquivo);
  26  	$m = 'bytes';
  27  	if ($tamanho>1024) {
  28  		$tamanho=round($tamanho/1024,2);
  29  		$m = 'KB';
  30  	} elseif($tamanho > 1024*1024){
  31  		$tamanho = round(($tamanho/1024)/1024,2);
  32  		$m = 'MB';
  33  	}
  34  	$arq .= "<img src='/imagens/arquivo.png'>&nbsp;<a href='$arquivo'>$arquivo</a> - $tamanho $m<br>";
  35  }
  36  echo $dir . $arq;
  37  
  38  closedir($dn);
  39  ?>
  40  
  41  

Adding files to an existing jar file

Adds files to an existing Zip file.

Overwrites zip entries with the same name as one of the new files.

The function renames the existing zip file to a temporary file and then adds all entries in the existing zip along with the new files, excluding the zip entries that have the same name as one of the new files.


Note: I'm not sure I used the best way to get a temp file. A snippet for that is welcome :)

   1  	
   2  	public static void addFilesToExistingZip(File zipFile,
   3  			 File[] files) throws IOException {
   4                  // get a temp file
   5  		File tempFile = File.createTempFile(zipFile.getName(), null);
   6                  // delete it, otherwise you cannot rename your existing zip to it.
   7  		tempFile.delete();
   8  
   9  		boolean renameOk=zipFile.renameTo(tempFile);
  10  		if (!renameOk)
  11  		{
  12  			throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
  13  		}
  14  		byte[] buf = new byte[1024];
  15  		
  16  		ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
  17  		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
  18  		
  19  		ZipEntry entry = zin.getNextEntry();
  20  		while (entry != null) {
  21  			String name = entry.getName();
  22  			boolean notInFiles = true;
  23  			for (File f : files) {
  24  				if (f.getName().equals(name)) {
  25  					notInFiles = false;
  26  					break;
  27  				}
  28  			}
  29  			if (notInFiles) {
  30  				// Add ZIP entry to output stream.
  31  				out.putNextEntry(new ZipEntry(name));
  32  				// Transfer bytes from the ZIP file to the output file
  33  				int len;
  34  				while ((len = zin.read(buf)) > 0) {
  35  					out.write(buf, 0, len);
  36  				}
  37  			}
  38  			entry = zin.getNextEntry();
  39  		}
  40  		// Close the streams		
  41  		zin.close();
  42  		// Compress the files
  43  		for (int i = 0; i < files.length; i++) {
  44  			InputStream in = new FileInputStream(files[i]);
  45  			// Add ZIP entry to output stream.
  46  			out.putNextEntry(new ZipEntry(files[i].getName()));
  47  			// Transfer bytes from the file to the ZIP file
  48  			int len;
  49  			while ((len = in.read(buf)) > 0) {
  50  				out.write(buf, 0, len);
  51  			}
  52  			// Complete the entry
  53  			out.closeEntry();
  54  			in.close();
  55  		}
  56  		// Complete the ZIP file
  57  		out.close();
  58  		tempFile.delete();
  59  	}

Java - imgFromJar

// Inserire un immagine presente nel file jar dell'applicazione

   1  
   2  try
   3  		{
   4  			icon = ImageIO.read(getClass().getResourceAsStream("imgs/icon.png")); // La preleva dal file jar
   5  			setIconImage(icon);
   6  		}
   7  		catch(IOException e)
   8  		{
   9  			e.printStackTrace();
  10  		}

compress files with rar

rar files with max compressiong and split them into 450k.
   1  
   2  rar a -s -v450 -m5 test.rar test/* 

Find all backup files in a directory

Find out where the backup files are. Backup files end with ~, for example test.php~

   1  
   2  find . -name *~ -print


For finding and deleting them:
   1  
   2  find . -name "*~" -exec rm {} \;


The \ is for preventing the "find: missing argument to `-exec'" error
« Newer Snippets
Older Snippets »
Showing 11-20 of 41 total