读取目录名,文件名和文件长度以及上次修改日期,JAVA

时间:2015-02-18 14:35:12

标签: java file-io simpledateformat

我正在尝试创建一个程序,该程序将目录名称作为命令行参数读取,并且对于目录中的每个文件,将打印以下信息:名称,长度和上次修改时间。

但不起作用,只显示相同文件的长度

 import java.io.File;
 import java.text.SimpleDateFormat;
 import java.util.Date;


public class x2 {


static void  show(String str) {
       System.out.println(str);
     }



public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
           File file = new File(args[0]);

        //Here we check whether the given argument is a directory
         if(file.isDirectory()) {
           System.out.println("Contents of: " + args[0]);

          //Here we initialize array con with the content of the
          //directory
           String dirContent[] = file.list();

           // date field ??
           Date date = new Date(file.lastModified());
           SimpleDateFormat sdf=new SimpleDateFormat("dd:MM:yyyy kk:mm:ss");


          //Here we go through the content of the directory one by one
           for(int i=0; i<dirContent.length; i++) {

              //Here we create an object of class File with the ith 
              //member of array con
              File auxf = new File(args[0] + "/" + dirContent[i]);

                //Here we check whether each content is a directory
                if(auxf.isDirectory()) {

                  //Here we initialize array newCon with the content of 
                 //each sub-directory
                   String newCon[] = auxf.list();

                   // file lenght ????
                   long length = file.length();

                  //Here we check whether the sub-directory is empty or not
                   if(newCon.length>0){
                     System.out.println("Content of "+args[0] +"\\"+ dirContent[i]+"\\");
                     for(int j=0; j<newCon.length; j++)
                      System.out.println(args[0] +"\\"+ dirContent[i] + "\\" + newCon[j]+" file length:"
                            + length +sdf.format(date) );
                    }
                   else
                     System.out.println(dirContent[i] + " is an empty directory.");       
                } else
                 System.out.println(dirContent[i] + " is a file.");
              } 
            }

             else
              System.out.println(args[0] + " is a file.");


           }catch(Exception e) {

            System.out.println("Usage: java showDir file_or_dir_name");
           }


}

}

有人可以帮我修复代码。

1 个答案:

答案 0 :(得分:0)

您实际上是在根目录上调用file.length()

public static void main(String[] args) {

  try {
    File file = new File(path);
    [...]
    for(int i=0; i<dirContent.length; i++) {
      File auxf = new File(path + "/" + aDirContent);
      [...]
      //Maybe you meant auxf.length() ?
      long length = file.length();