File类获取功能的方法

package com.chunzhi.Test01.File;

import java.io.File;

/*
    File类获取功能的方法
        public String getAbsolutePath():返回此File的绝对路径名字符串
        public String getPath():将此File转换为路径名字符串
        public String getName():返回由此File表示的文件或文件夹(目录)的名称
        public long length():返回由此File表示的文件的长度(大小)
 */
public class Test03File {
    public static void main(String[] args) {
        method04();
    }
    /*
        public String getAbsolutePath():返回此File的绝对路径名字符串
        获取构造方法中传递的路径
        无论路径是绝对的还是相对的,getAbsolutePath方法返回的都是绝对路径
     */
    public static void method01() {
        File f = new File("C:\\Other\\IdeaProjects\\API-Two");
        File absoluteFile = f.getAbsoluteFile();
        System.out.println(absoluteFile); // C:\Other\IdeaProjects\API-Two

        File f1 = new File("a.txt");
        File absoluteFile1 = f1.getAbsoluteFile();
        System.out.println(absoluteFile1); // C:\Other\IdeaProjects\API-Two\a.txt
    }
    /*
        public String getPath():将此File转换为路径名字符串(将路径原封不动打印输出)
        获取构造方法中传递的路径
     */
    public static void method02() {
        File f = new File("C:\\Other\\IdeaProjects\\API-Two\\a.txt");
        File f1 = new File("a.txt");
        System.out.println(f.getPath()); // C:\Other\IdeaProjects\API-Two\a.txt
        System.out.println(f1.getPath()); // a.txt

        // File里面的toString方法,就是调用的getPath方法
        System.out.println(f1.toString()); // a.txt
    }
    /*
        public String getName():返回由此File表示的文件或目录的名称
        获取的就是构造方法传递路径的结尾部分(文件/文件夹)
     */
    public static void method03() {
        File f = new File("C:\\Other\\IdeaProjects\\API-Two\\a.txt");
        File f1 = new File("C:\\Other\\IdeaProjects\\API-Two");
        System.out.println(f.getName()); // a.txt
        System.out.println(f1.getName()); // API-Two
    }
    /*
        public long length():返回由此File表示的文件的长度
        获取的是构造方法指定的文件的大小,以字节为单位
        注意:
            文件夹是没有大小概念的,不能获取文件夹的大小
            如果构造方法中给出的路径不存在,那么length方法返回0
     */
    public static void method04() {
        File f = new File("C:\\Other\\IdeaProjects\\API-Two\\a.txt");
        File f1 = new File("C:\\Other\\IdeaProjects");
        System.out.println(f.length()); // 57
        System.out.println(f1.length()); // 0
    }
}

 

posted @ 2020-11-15 21:50  春志  阅读(354)  评论(0)    收藏  举报