File类 获取文件属性

package Chapter8.ShiLi.Demo1;

import java.io.File;

public class FileMethods {

  public static void main(String[] args) {
    FileMethods fm = new FileMethods();
      File file = new File("D:\\text.txt");
      fm.showFileInfo(file);

}

public void showFileInfo(File file) {
  if (file.exists()) { // 判断文件或目录是否存在
  if (file.isFile()) { // 如果是文件
    System.out.println("名称:" + file.getName());
    System.out.println("相对路径:" + file.getPath());
    System.out.println("绝对路径:" + file.getAbsolutePath());
    System.out.println("文件大小:" + file.length() + "字节");
  }
  if (file.isDirectory()) {
    System.out.println("此文件是目录。");
  }


  } else {
    System.out.println("文件不存在");
  }

 }
}

posted @ 2018-02-19 21:02  医者心  阅读(1649)  评论(0编辑  收藏  举报