File类使用技巧

File类操作文本

创建 new File(String pathName);
在创建时 将文件的路径名称写成字符串格式,在后面的小括号里写

new File(String parent,String child);
在创建时 将父文件路径与子文件路径 的地址名称拼接,进行创建

    //File(String pathname): 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
    File f1 = new File("E:\\itcast\\java.txt");
    System.out.println(f1);

    //File(String parent, String child): 从父路径名字符串和子路径名字符串创建新的 File实例
    File f2 = new File("E:\\itcast","java.txt");
    System.out.println(f2);

    //File(File parent, String child): 从父抽象路径名和子路径名字符串创建新的 File实例
    File f3 = new File("E:\\itcast");
    File f4 = new File(f3,"java.txt");
    System.out.println(f4);
  • 绝对路径

    是一个完整的路径,从盘符开始

  • 相对路径

    是一个简化的路径,相对当前项目下的路径
    // 是一个完整的路径,从盘符开始
    File file1 = new File(“D:\itheima\a.txt”);

      // 是一个简化的路径,从当前项目根目录开始
      File file2 = new File("a.txt");
      File file3 = new File("模块名\\a.txt");
    

File类创建功能
public boolean createNewFile(); 这个路径名没有文件,就创建新文件
public boolean mkdir (); 创建一个单级文件夹
public boolean mkdirs();创建多级文件夹
public boolean delete();删除文件夹、或者文件

File类判断和获取功能
boolean isDirectory(); 判断路径是不是个文件夹
boolean isFile(); 判断路径是不是个文件

String getAbsolutePath(); 以String类型 返回文件或文件夹的绝对路径
String getPath(); 以String类型 返回文件或文件夹相对路径。
String getName(); 获取这个路径文件或文件夹的名称
File[ ] listFiles(); 将这个路径中的文件夹和文件的名称封装到 File类型的数组。由此来获取这个路径上和所有的文件和文件夹。

将 C盘中所有文件销毁 没有访问权限的文件也可以删除
-----------------------------慎用--------------------------
public static void main(String[] args) {
File src = new File(“C:”);
deleteDir(src); }
private static void deleteDir(File src) {
File[] files = src.listFiles();
for (File file : files) {
if(file.isFile()){
file.delete();
}else{
deleteDir(file); } }
src.delete(); }

++++++++++++++++++++++++++++++++++++++++++++++++++++

统计 盘中 所有 文件 的类型

public static void main(String[] args) {
File file = new File(“filemodule”);
HashMap<String, Integer> hm = new HashMap<>();
getCount(hm, file);
System.out.println(hm);
}

private static void getCount(HashMap<String, Integer> hm, File file) {
    File[] files = file.listFiles();
    for (File f : files) {
        if(f.isFile()){
            String fileName = f.getName();
            String[] fileNameArr = fileName.split("\\.");
            if(fileNameArr.length == 2){
                String fileEndName = fileNameArr[1];
                if(hm.containsKey(fileEndName)){
                    Integer count = hm.get(fileEndName);
                    count++;
                    hm.put(fileEndName,count);
                }else{
                    hm.put(fileEndName,1);   }  }  }else{
            getCount(hm,f);  } } }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

普希托夫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值