Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Saturday, April 21, 2007

Java/Perl - Directory handles

With Perl, one way to get a list of names in a given directory is to use a directory handle. On my Fedora box, Perl displays "." and ".." while Java does not.

Perl

#!/usr/bin/perl
use strict;
use warnings;

my $dir = '/home/kl93';
opendir DH, $dir or die "Cannot open $dir: $!";
foreach my $file (readdir DH) {
next if $file =~ /^\.\.?$/; # skip . and ..
print "$file\n";
}
close DH;


Java

import java.io.*;

public class ReadDir
{
public static void main(String[] args) throws Exception
{

File file = new File("/home/kl93");

if( !file.exists() || !file.canRead() )
{
System.out.println("Can't read " + file);
return;
}

if( file.isDirectory() ) {
String[] files = file.list();
for(int i=0; i<files.length; i++)
System.out.println(files[i]);
}
else {
System.out.println(file + " is not a directory");
}
}
}


If you want to display filenames based on some sort of criteria - like all files with the .java extension for example - then it's often easiest to use a regular expression.

Perl

#!/usr/bin/perl
use strict;
use warnings;

my $dir = '/home/kl93';
opendir DH, $dir or die "Cannot open $dir: $!";
foreach my $file (readdir DH) {
next unless $file =~ /\.java$/;
print "$file\n";
}
close DH;


Java

import java.io.*;
import java.util.regex.*;

public class ReadDir2
{
public static void main(String[] args) throws Exception
{

File file = new File("/home/kl93");

if( !file.exists() || !file.canRead() )
{
System.out.println("Can't read " + file);
return;
}

if( file.isDirectory() ) {
String[] files = file.list();
for(int i=0; i<files.length; i++)
{
if(files[i].matches("^.*\\.java$"))
System.out.println(files[i]);
}
}
else {
System.out.println(file + " is not a directory");
}
}
}


Or


import java.io.*;
import java.util.regex.*;

public class ReadDir3
{
public static void main(String[] args) throws Exception
{

File file = new File("/home/kl93");

if( !file.exists() || !file.canRead() )
{
System.out.println("Can't read " + file);
return;
}

if( file.isDirectory() ) {
String[] files = file.list();
Pattern pattern = Pattern.compile("\\.java$");
Matcher matcher;
for(int i=0; i<files.length; i++)
{
matcher = pattern.matcher(files[i]);
if(matcher.find())
System.out.println(files[i]);
}
}
else {
System.out.println(file + " is not a directory");
}
}
}


Sort (ascending)

Perl

#!/usr/bin/perl
use strict;
use warnings;

my $dir = '/home/kl93';
opendir DH, $dir or die "Cannot open $dir: $!";
foreach my $file (sort readdir(DH)) {
print "$file\n";
}
close DH;


Sort desending


#!/usr/bin/perl
use strict;
use warnings;

my $dir = '/home/kl93';
opendir DH, $dir or die "Cannot open $dir: $!";
foreach my $file (reverse(sort readdir(DH))) {
print "$file\n";
}
close DH;

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels