迷新白的博客 迷新白的博客
首页
随笔
  • Vuepress
  • Springboot
  • 开发工具
  • 系统工具
读吧
  • 智能浇花系统 (opens new window)
  • 用户中心系统 (opens new window)
  • 关于
  • 友情链接
GitHub (opens new window)

迷新白

愿你平安
首页
随笔
  • Vuepress
  • Springboot
  • 开发工具
  • 系统工具
读吧
  • 智能浇花系统 (opens new window)
  • 用户中心系统 (opens new window)
  • 关于
  • 友情链接
GitHub (opens new window)
  • 后端基础

  • Java

    • 优化数据库和前端的交互
    • IO流和使用文件流
    • Java类型File和Files的使用
      • File类型
      • Files类型
        • 主要特点:
    • Java类型List和Map
    • Java异常处理
  • 后端
  • Java
迷新白
2025-08-01
目录

Java类型File和Files的使用

# Java类型File和Files的使用

# File类型

File是文件和路径名的抽象表示

引用包

 java.io.File
1

一个File代表的是硬盘中的一个路径或者一个文件

无论路径下是否存在文件或目录都不影响File对象的创建

        File file1 = new File("D:\\aaa\\a.txt");
        File file2 = new File("D:\\aaa","a.txt");
        File file3 = new File("a.txt");
/*
file1表示通过给定的路径名 字符串转换为抽象类路径 来创建新的实例

file2表示从父路径字符串 和 子路径字符串创建新的File实例

file3表示从父抽象路径名 和 子路径名字符串创建新的File实例
*/
        System.out.println(file1);
        System.out.println(file2);
        System.out.println(file3);

输出结果:
            D:\aaa\a.txt
            D:\aaa\a.txt
            a.txt
                
            file1.getAbsolutePath()//返回File的绝对路径名 字符串
            file1.getName()  //返回此File表示的文件或目录的名称
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Files类型

Files 是 Java 7 引入的工具类,属于 java.nio.file 包

与 File 不同,Files 提供了更高级和强大的功能,能够处理文件和目录的多种操作

# 主要特点:

结合 Path 使用:Files 类的静态方法通常需要与 Path 对象配合使用,而不是 File 对象。

Files.createFile(filePath);  // 创建文件
Files.delete(filePath);  // 删除文件
Files.copy(filePath, targetPath);  // 复制文件
Files.move(filePath, targetPath);  // 移动/重命名文件
Files.readAllLines(filePath);  // 读取文件内容
Files.write(filePath, "content".getBytes());  // 写入文件内容
1
2
3
4
5
6

.Files createTempFile() 方法返回新创建的临时文件的路径对象。

而toFile()方法的作用是将这个Path对象转换为File对象(java.io.File)。

Java java.nio.file.Files createTempFile() 方法 | 菜鸟教程 (runoob.com) (opens new window)

IO流和使用文件流
Java类型List和Map

← IO流和使用文件流 Java类型List和Map→

最近更新
01
IO流和使用文件流
08-01
02
Java类型List和Map
08-01
03
Java异常处理
08-01
更多文章>
Theme by Vdoing | Copyright © 2022-2025 迷新白 | 的博客
sitemap icon by Icons8
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式