读取文件夹并提供文件夹中存在的所有文件的详细信息

时间:2015-06-08 11:49:30

标签: java

我得到了一个程序,它应该读取给定文件夹中的所有文件,并提供文件详细信息,如文件名,文件大小,创建的日期和时间,文件位置作为输出。如果给定文件夹中有任何子文件夹,那么它也应该确定该子文件夹中存在的文件的详细信息。

1 个答案:

答案 0 :(得分:0)

package FileDetails;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;``


public class FileDetails 
{
    public static void filelist(final File folder) throws IOException
    {
        for (final File fileEntry : folder.listFiles())
        {
            if(fileEntry.isDirectory())
            {
                filelist(fileEntry);
            }
            else
            {
                //To get file name

                System.out.println("File name is : " + fileEntry.getName());

                //To get file extension

                String fileName = fileEntry.getName();
                if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
                {
                    System.out.println("Extension of file is : " + fileName.substring(fileName.lastIndexOf(".")+1));
                }

                //To get file size

                double bytes = fileEntry.length();
                double kilobytes = (bytes / 1024);
                System.out.println("Size of the file is : " + kilobytes + " KB");

                //To get file times

                Path path = fileEntry.toPath();
                BasicFileAttributes attr = Files.readAttributes(path,BasicFileAttributes.class);

                System.out.println("Creation time  :  " + attr.creationTime());
                System.out.println("Last Access time  :  " + attr.lastAccessTime());
                System.out.println("Last Modified time  :  " + attr.lastModifiedTime() + "\n\n");


            }
        }
    }
    public static void main(String[] arg) throws IOException
    {
        final File folder = new File("folder location");
        filelist(folder);
    }
}