(File operation) Obtain file information

Get file information

In addition to file operations, you can also use the File class to obtain some information provided by the file itself. You can obtain the following:

  • Whether the file is readable: public boolean canRead();
  • Whether the file can be written: public boolean canWrite();
  • Get the file length: public long length(); This method returns long type data.
  • Last modified date and time: public long lastModified();
  • Determine whether it is a directory: public boolean isDirectory();
  • Determine whether it is a file: public boolean isFile();
  • List the contents of the directory: public File[] listFiles();

 example:

Main method:

public static void main(String[] args) throws IOException {
        File file = new File("E:"+File.separator+"183441"); //File.separator表示分隔符
        System.out.println("文件是否可读"+file.canRead());
        System.out.println("文件是否可写"+file.canWrite());
        System.out.println("文件的大小"+MathUtil.round(file.length()/(double)1024/1024,2)+"M");
        System.out.println("文件最后的修改时间"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
        System.out.println("是否是目录"+file.isDirectory());
        System.out.println("是否是文件"+file.isFile());
        System.out.println("目录下还有哪些内容?");

        if(file.isDirectory()) {    //当前是一个目录
            File[] fileData = file.listFiles(); //列出目录中的全部内容
            for(File file1 : fileData){
                System.out.println(file1);
            }
        }
    }

Rounding category:

class MathUtil{
    private MathUtil(){}
    public static double round(double num,int scale){
        return Math.round(Math.pow(10,scale) * num) / Math.pow(10,scale);
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112756540