001: /**
002: Display the contents of the current working directory.
003: The format is similar to the Unix ls -l
004: <em>This is an example of a bsh command written in Java for speed.</em>
005:
006: @method void dir( [ String dirname ] )
007: */package bsh.commands;
008:
009: import java.io.*;
010: import bsh.*;
011: import java.util.Date;
012: import java.util.Vector;
013: import java.util.GregorianCalendar;
014: import java.util.Calendar;
015:
016: public class dir {
017: static final String[] months = { "Jan", "Feb", "Mar", "Apr", "May",
018: "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
019:
020: public static String usage() {
021: return "usage: dir( String dir )\n dir()";
022: }
023:
024: /**
025: Implement dir() command.
026: */
027: public static void invoke(Interpreter env, CallStack callstack) {
028: String dir = ".";
029: invoke(env, callstack, dir);
030: }
031:
032: /**
033: Implement dir( String directory ) command.
034: */
035: public static void invoke(Interpreter env, CallStack callstack,
036: String dir) {
037: File file;
038: String path;
039: try {
040: path = env.pathToFile(dir).getAbsolutePath();
041: file = env.pathToFile(dir);
042: } catch (IOException e) {
043: env.println("error reading path: " + e);
044: return;
045: }
046:
047: if (!file.exists() || !file.canRead()) {
048: env.println("Can't read " + file);
049: return;
050: }
051: if (!file.isDirectory()) {
052: env.println("'" + dir + "' is not a directory");
053: }
054:
055: String[] files = file.list();
056: files = StringUtil.bubbleSort(files);
057:
058: for (int i = 0; i < files.length; i++) {
059: File f = new File(path + File.separator + files[i]);
060: StringBuffer sb = new StringBuffer();
061: sb.append(f.canRead() ? "r" : "-");
062: sb.append(f.canWrite() ? "w" : "-");
063: sb.append("_");
064: sb.append(" ");
065:
066: Date d = new Date(f.lastModified());
067: GregorianCalendar c = new GregorianCalendar();
068: c.setTime(d);
069: int day = c.get(Calendar.DAY_OF_MONTH);
070: sb.append(months[c.get(Calendar.MONTH)] + " " + day);
071: if (day < 10)
072: sb.append(" ");
073:
074: sb.append(" ");
075:
076: // hack to get fixed length 'length' field
077: int fieldlen = 8;
078: StringBuffer len = new StringBuffer();
079: for (int j = 0; j < fieldlen; j++)
080: len.append(" ");
081: len.insert(0, f.length());
082: len.setLength(fieldlen);
083: // hack to move the spaces to the front
084: int si = len.toString().indexOf(" ");
085: if (si != -1) {
086: String pad = len.toString().substring(si);
087: len.setLength(si);
088: len.insert(0, pad);
089: }
090:
091: sb.append(len.toString());
092:
093: sb.append(" " + f.getName());
094: if (f.isDirectory())
095: sb.append("/");
096:
097: env.println(sb.toString());
098: }
099: }
100: }
|