Start Search Contents Index Links About
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 dirString args[] )
  {
    String homeDir = "";
    File file;
    File fileList[];
    String fileName;
    String fileDate;
    long fileLength;
    boolean isDir;
    boolean isHidden;
    
    DateFormat df;
    
    checkArgsargs );

    //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 FilehomeDir );
    fileList = file.listFiles();
    iffileList == null )
    {
      System.out.println("dir.dir - Error accessing current directory.");
      System.exit(1);
    }
    
    //Set the date format
    df = DateFormat.getDateTimeInstanceDateFormat.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.formatnew DatefileList[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.printlnfileName );
        }
      }
    }
    
  }
  
  /**
  * Checks the arguments passed to the main method
  @param args[] the String array passed to the main methods
  */
  private void checkArgsString 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 -)
      ifarray[0== '/' )
      {
        //is the long listing format requested?
        ifarray[1== 'b' )
        {
          bareFormat = true;
        }
      }
    }

  }
  
  public static void mainString args[] )
  {
    new dirargs );
  }

}


site: Håvard Rast Blok
mail:
updated: 27 July 2007