H5W3
当前位置:H5W3 > 其他技术问题 > 正文

Java实现Windows的dir命令

        为做一个文件管理系统所实现的一个很粗糙的小例子,感觉还是有研究价值的。

        下面是源代码:

        import java.util.Comparator;        import java.io.File;        /**        * Created by IntelliJ IDEA.<br>        * <b>User</b>: leizhimin<br>        * <b>Date</b>: 2008-7-18 22:43:44<br>        * <b>Note</b>: 文件排序,按照先目录后文件方式排        */        public class FileComparator implements Comparator<File> {

            public int compare(File o1, File o2) {                if (o1.isDirectory() && o2.isDirectory()) return o1.compareTo(o2);                else if(o1.isDirectory() && !o2.isDirectory()) return -1;                else if(!o1.isDirectory() && o2.isDirectory()) return 1;                else return o1.compareTo(o2);            }        }

        import java.io.File;        import java.util.*;        import java.sql.Date;        import java.text.DateFormat;        import java.text.SimpleDateFormat;        import java.text.NumberFormat;        /**        * Created by IntelliJ IDEA.<br>        * <b>User</b>: leizhimin<br>        * <b>Date</b>: 2008-7-18 22:02:30<br>        * <b>Note</b>: 模拟dir测试的例程        */        public class TestFile {            public static DateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm”);            int nl = 18;            public static void main(String args[]) {                test();            }            public static void test() {                System.out.println(“———-test()———-“);                File file = new File(“F:\\SOFT_DEV”);        //        file.isDirectory();        //        System.out.println(File.pathSeparator);        //        System.out.println(File.pathSeparatorChar);        //        System.out.println(File.separator);        //        System.out.println(File.separatorChar);                FileComparator fc = new FileComparator();                File[] lf = file.listFiles();                Arrays.sort(lf, fc);    //数组排序                for (File f : lf) {                    String dataStr = df.format(new Date(f.lastModified()));

                    if (f.isDirectory()) {                        System.out.print(dataStr + ”  <DIR>       “);

                    } else {                        System.out.print(dataStr + ”  ” + getFormatString(String.valueOf(NumberFormat.getInstance().format(f.length()))));                    }                    System.out.println(”  ” + f.getName());                }

            }            //格式化函数            public static String getFormatString(String s) {                int nb = 12 – s.length();                StringBuilder sb = new StringBuilder();                if (nb > 0) {                    for (int n = 1; n <= nb; n++) {                        sb = sb.append(” “);                    }                }                return sb.append(s).toString();            }        }

本文地址:H5W3 » Java实现Windows的dir命令

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址