File类的介绍和常用方法

File类的介绍:

File类构造方法:

常用的有三种:

1 、File(String pathname):通过路径名创建一个新 File 实例。

2、File(File parent, String child):根据父目录路径File实例和子目录或文件路径创建一个新 File 实例。

3、File(String parent, String child) :根据父目录路径和子目录或文件路径创建一个新 File 实例。

public class FileDemo1 {
    public static void main(String[] args) throws IOException {
        // 1 File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的File实例
        File f1 = new File("F:\\a.txt");
        System.out.println(f1); // F:\a.txt
 
        // 2 File(String parent, String child) 父路径名字符串 和 子路径名字符串
        File f2 = new File("F:\\abc", "a.txt");
        System.out.println(f2); // F:\abc\a.txt
 
        // 3 File(File parent, String child) 父抽象路径名 和 子路径字符串
        File f3 = new File(new File("F:\\abc\\a"), "a.txt");
        System.out.println(f3); // F:\abc\a\a.txt
 
        /*错误示范:File类构造函数的本质就是将两个字符串连接起来,不会检验路径是否正确*/
        File f4 = new File(new File("F:\\abc\\x.jpg"), "aa.txt");
        System.out.println(f4); // F:\abc\x.jpg\aa.txt
    }
}

其中的正常方法使用:

getAbsolutePath():获取绝对路径

public class FileTest2 {
    public static void main(String[] args) {
    File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
    String absolutePath1 = f1.getAbsolutePath();
    System.out.println("文件的绝对路径"+absolutePath1);//绝对磁盘路径 
   }
​}

getName():返回此对象表示的文件或目录最后一级文件夹名称

public class FileTest2 {
    public static void main(String[] args) {
    File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
    String name1 = f1.getName();//获取文件名,即你定位的元素
    System.out.println("文件名称:"+name1);
 }
}

getPath(): 返回File对象所表示的字符串路径

public class FileTest2 {
    public static void main(String[] args) {
    File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
    String path1 = f1.getPath();
    System.out.println("文件的路径"+path1);
   }
}

exists(): 判断文件/文件夹是否存在

public class FileTest2 {
    public static void main(String[] args) {
    File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
     System.out.println(f1.exists());
   }
}

isDirectory(): 判断此File对象代表的路径表示是不是文件夹,只有File对象代表路径存在且是一个目录时才返回true,否则返回false

public class FileTest2 {
    public static void main(String[] args) {
    File f1=new File("D:/aa/hello.txt");//创建了 文件 映射对象
    System.out.println(f1.isDirectory());
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值