JAVA中File Path Files类的使用

直接上代码:
 

package test;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class Test {
    public static void main(String[] args) throws IOException {
        /**
         * File和Path都可以代表文件或目录
         */
        //**********************Path****************************
        //创建Path对象的两种方式,代表一个目录或文件
        Path p1 = Paths.get("C:\\Users\\86150\\Desktop\\hello.txt");
        System.out.println(p1);
        Path p2 = Path.of("C:\\Users\\86150\\Desktop\\hello.txt");
        System.out.println(p2);
        //把Path对象转为File对象
        File file = p1.toFile();
        //获取父路径
        Path parentPath = p1.getParent();
        System.out.println(parentPath);
        //获取文件名/目录名
        Path itself = p1.getFileName();
        System.out.println(itself.toString());

        //***********************Files工具类**************************
        //一次性读取文件中所有字节
        byte[] bytes = Files.readAllBytes(p1);
        System.out.println(new String(bytes, "utf-8"));
        //读取字符流
        String str = Files.readString(p1);
        System.out.println(str);
        //按行读取,把每一行当成一个元素组成字符串List
        List<String> list = Files.readAllLines(p1);

        //以字节为单位写入数据,第三个参数是选项
        byte[] bytes1 = "woshiliqighao".getBytes();
        Path path1 = Path.of("C:\\Users\\86150\\Desktop\\hello1.txt");
        Files.write(path1, bytes1, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        //把字符串写入文件
        String str1 = "hhaha";
        Path path2 = Path.of("C:\\Users\\86150\\Desktop\\hello2.txt");
        Files.writeString(path2, str1, StandardOpenOption.CREATE);
        //把List<String>写到文件;略;
        //Files还有三个方法与File类相对应,分别是createFile()  createDirectory()  createDirectories()

        //**********************File类****************************
        //文件
        File file1 = new File("C:\\Users\\86150\\Desktop\\hello3.txt");
        //在磁盘上创建新文件
        file1.createNewFile();
        //删除文件
        file1.delete();
        System.out.println(file1.isFile());
        System.out.println(file1.isDirectory());
        System.out.println(file1.exists());

        //目录
        File file2 = new File("C:\\Users\\86150\\Desktop\\hello\\haha");
        System.out.println(file2.mkdir());
        System.out.println(file2.mkdirs());//mkdirs会创建所需中间目录
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值