簡體   English   中英

讀取目錄名,文件名和文件長度以及上次修改日期,JAVA

[英]reading directory name, file name and length of file and last modified date , JAVA

我正在嘗試創建一個程序,它將目錄的名稱作為命令行參數讀取,並且對於目錄中的每個文件,將打印以下信息:名稱,長度和上次修改時間。

但不起作用,只顯示相同文件的長度

 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");
           }


}

}

有人可以幫我修復代碼。

您實際上是在根目錄上調用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM