//File: ls.java //CS 471 - Operating Systems Project //Dennis Pereira, Ely Soto, John Cavalieri import java.io.*; import java.text.DateFormat; import java.util.Date; // This file is used to output the contents of a directory public class ls extends VMachine { public ls() { } public void run() { try { File fileObject; String bytelength; String time,date; int dircount = 0; int filecount = 0; long totalbytecount = 0; if (args.length == 0) // If no argument get the current path { fileObject = new File(sysapi.findUser(owner).getcurrentPath()); } else // If it has arguments add the argument to the current path { fileObject = new File(sysapi.findUser(owner).getcurrentPath() + args[0]); } if(fileObject.isDirectory()) // Only if it's a directoy continue { File[] listing = fileObject.listFiles(); for(int x = 0; x < listing.length; x++) { if(listing[x].isDirectory()) // If it's a directory found { dircount++; // Increment directory count // Get time the directory was created time = new String(DateFormat.getTimeInstance().format(new Date(listing[x].lastModified()))); for(int i=0;time.length() < 11;i++) { time = " " + time; // output the time } date = new String(DateFormat.getDateInstance().format(new Date(listing[x].lastModified()))); for(int i=0;date.length() < 12;i++) { date = " " + date; // Output the date } sysapi.Write(OUT,time + " " + date + " [DIR] " + " " + listing[x].getName() + "\n"); } else if(listing[x].isFile()) // If it's a file that is found { filecount++; // Increment file count totalbytecount += listing[x].length(); // Get byte count bytelength = new String().valueOf(listing[x].length()); for(int i=0;bytelength.length() < 8;i++) { bytelength = " " + bytelength; } time = new String(DateFormat.getTimeInstance().format(new Date(listing[x].lastModified()))); for(int i=0;time.length() < 11;i++) { time = " " + time; // output the time } date = new String(DateFormat.getDateInstance().format(new Date(listing[x].lastModified()))); for(int i=0;date.length() < 12;i++) { date = " " + date; // output the date } sysapi.Write(OUT, time + " " + date + " " + bytelength + " " + listing[x].getName() + "\n"); } } if(filecount > 0) // if files are found print the total number of bytes for all the files { sysapi.Write(OUT,new String().valueOf(totalbytecount) + " Bytes in " + new String().valueOf(filecount) + " File(s)\n"); } if(dircount > 0) // output number of directories { sysapi.Write(OUT,new String().valueOf(dircount) + " Directories(s)\n"); } } else // Error statement if directory doesn't exist. { sysapi.Write(OUT,"Error -- Directory does not exist.\n"); } sysapi.Exit(vmh,owner); } catch (Exception err) { System.out.println("ls threw Exception: " + err); } } }