 |
|
|
dir.java
|
/*
* Author: Havard Rast Blok
* E-mail: 
* Web : www.rememberjava.com
*/
import java.io.File;
import java.text.DateFormat;
import java.util.Date;
/**
* Lists the files in the current directory. One file per line.
* Uses command line parameters to switch between modes.
* Similuar to "dir /b" or "dir" in DOS-prompt of Windows or
* "ls -1" (-one) in Linux ("ls -l" (lowercase L) not implemented)
*/
public class dir
{
private boolean bareFormat;
public dir( String args[] )
{
String homeDir = "";
File file;
File fileList[];
String fileName;
String fileDate;
long fileLength;
boolean isDir;
boolean isHidden;
DateFormat df;
checkArgs( args );
//Get the current directory
try
{
homeDir = System.getProperty( "user.dir" );
}
catch(Exception e)
{
System.out.println("dir.dir - Unable to retrieve current directory: "+e);
System.exit(1);
}
//Get file names of the current directory
file = new File( homeDir );
fileList = file.listFiles();
if( fileList == null )
{
System.out.println("dir.dir - Error accessing current directory.");
System.exit(1);
}
//Set the date format
df = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT );
//List the files in the current directory. One file per line.
for(int i = 0; i < fileList.length; i++)
{
//check if file is hidden...
isHidden = fileList[i].isHidden();
//...and show only file which are not
if( !isHidden )
{
fileName = fileList[i].getName();
//show long listing for only names
if( !bareFormat )
{
fileDate = df.format( new Date( fileList[i].lastModified() ) );
fileLength = fileList[i].length();
isDir = fileList[i].isDirectory();
//Notice that the tabulation with large files is not very good.
System.out.println(fileDate + "\t" + (isDir?"<DIR>\t":" \t"+fileLength) + "\t" + fileName);
}
else
{
System.out.println( fileName );
}
}
}
}
/**
* Checks the arguments passed to the main method
* @param args[] the String array passed to the main methods
*/
private void checkArgs( String args[] )
{
char array[];
//check all the arguments
for(int i = 0; i < args.length; i++)
{
array = args[i].toCharArray();
//check if this argument is an option (starting with -)
if( array[0] == '/' )
{
//is the long listing format requested?
if( array[1] == 'b' )
{
bareFormat = true;
}
}
}
}
public static void main( String args[] )
{
new dir( args );
}
}
|
|
|
 |