Java Files的常用方法都有哪些?

Java Files的常用方法都有哪些?

在Java中,java.nio.file.Files 类提供了许多用于操作文件和目录的静态方法。以下是一些常用的方法,以及相应的代码示例:

1. 读取文件内容:

  • readAllLines(Path path, Charset cs) 读取文件的所有行。

    Path filePath = Paths.get("example.txt");
    List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
    
  • readAllBytes(Path path) 读取文件的所有字节。

    Path filePath = Paths.get("example.txt");
    byte[] fileBytes = Files.readAllBytes(filePath);
    

2. 写入文件内容:

  • write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) 将字符串写入文件。

    Path filePath = Paths.get("output.txt");
    List<String> content = Arrays.asList("Line 1", "Line 2", "Line 3");
    Files.write(filePath, content, StandardCharsets.UTF_8);
    
  • write(Path path, byte[] bytes, OpenOption... options) 将字节数组写入文件。

    Path filePath = Paths.get("output.txt");
    byte[] contentBytes = "Hello, World!".getBytes(StandardCharsets.UTF_8);
    Files.write(filePath, contentBytes);
    

3. 复制和移动文件:

  • copy(Path source, Path target, CopyOption... options) 复制文件。

    Path sourcePath = Paths.get("source.txt");
    Path targetPath = Paths.get("target.txt");
    Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
    
  • move(Path source, Path target, CopyOption... options) 移动文件。

    Path sourcePath = Paths.get("source.txt");
    Path targetPath = Paths.get("target.txt");
    Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
    

4. 删除文件和目录:

  • delete(Path path) 删除文件或目录。

    Path filePath = Paths.get("example.txt");
    Files.delete(filePath);
    
  • deleteIfExists(Path path) 如果存在,则删除文件或目录。

    Path filePath = Paths.get("example.txt");
    Files.deleteIfExists(filePath);
    

5. 检查文件和目录属性:

  • isDirectory(Path path, LinkOption... options) 判断给定路径是否为目录。

    Path dirPath = Paths.get("example_directory");
    boolean isDirectory = Files.isDirectory(dirPath);
    
  • isRegularFile(Path path, LinkOption... options) 判断给定路径是否为普通文件。

    Path filePath = Paths.get("example.txt");
    boolean isRegularFile = Files.isRegularFile(filePath);
    

6. 获取文件和目录信息:

  • exists(Path path, LinkOption... options) 判断给定路径是否存在。

    Path filePath = Paths.get("example.txt");
    boolean exists = Files.exists(filePath);
    
  • size(Path path) 获取文件的大小。

    Path filePath = Paths.get("example.txt");
    long fileSize = Files.size(filePath);
    

这些只是 java.nio.file.Files 类的一部分常用方法。根据具体需求,可以选择合适的方法进行文件和目录操作。

  • 18
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

学习资源网

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

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

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

打赏作者

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

抵扣说明:

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

余额充值