Java开发笔记

一、参数校验

1、校验json字符串是否符合规范

  (1)业务场景:接收前端传输过来的json串,需要将其写入数据库,写入之前需要校验其是否能够转换成对应实体类,以便后续从数据库读取
  (2)方法:借助jackson中的反序列化工具,当字符串不符合json格式或出现实体类中不存在的字段时,会报错。步骤如下:
  【1】引入依赖

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>

注意:如果你的项目已经引入了spring-boot-starter依赖,那么就不需要重复引入,spring-boot-starter已自带jackson
在这里插入图片描述
  【2】校验代码

public class User {
    private int id;
    private String name;

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
    @Test
    public void test() {
        String json1 = "{\"id\":1,\"name\":\"张三\",\"age\":18}";
        String json2 = "acg";
        String json3 = "{\"id\":1,\"name\":\"张三\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            objectMapper.readValue(json1, User.class);
            System.out.println("json1校验成功!!");
        } catch (JsonProcessingException e) {
            System.out.println("json1校验失败!!");
        }
        try {
            objectMapper.readValue(json2, User.class);
            System.out.println("json2校验成功!!");
        } catch (JsonProcessingException e) {
            System.out.println("json2校验失败!!");
        }
        try {
            objectMapper.readValue(json3, User.class);
            System.out.println("json3校验成功!!");
        } catch (JsonProcessingException e) {
            System.out.println("json3校验失败!!");
        }
    }

  【3】运行结果
   json1多出了一个age字段,校验不通过
   json2格式错误,校验不通过
   json3格式正确且User类包含该json所有字段,校验通过
注意:实体类必须提供无参构造方法以及set方法

json1校验失败!!
json2校验失败!!
json3校验成功!!

二、文件系统学习

1、Path类:优雅灵活地使用文件

  在为项目开发一些便利工具时,时常需要对文件进行创建和读写。比如我现在需要创建一个txt文件来存储一些文本信息,在一开始,我使用了以下方法来创建。这种方法有一个缺点,需要分离文件上层目录路径和文件路径

public static void createFileTest() {
        // 文件父目录路径
        String parentDirPath = "D:/testDir/";
        // 文件名称和类型
        String filePath = "D:/testDir/1.txt";
        // 定义父目录File
        File parentFile = new File(parentDirPath);
        // 定义文件File
        File file = new File(filePath);
        // 创建目录
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        // 创建文件
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

 上面例子最繁琐的地方如下,重复写了文件的上层目录路径部分,写起来繁琐,看起来也不优雅:

        // 文件父目录路径
        String parentDirPath = "D:/testDir/";
        // 文件名称和类型
        String filePath = "D:/testDir/1.txt";
        // 定义父目录File
        File parentFile = new File(parentDirPath);
        // 定义文件File
        File file = new File(filePath);

 如果后续还需要再使用到文件的所在的目录路径和文件名,那么在定义上将会更加繁琐:

        // 文件父目录路径
        String parentDirPath = "D:/testDir/";
        // 文件名称
        String fileName = "1.txt";
        // 文件名称和类型
        String filePath = parentDirPath + fileName;
        // 定义父目录File
        File parentFile = new File(parentDirPath);
        // 定义文件File
        File file = new File(filePath);

 为了解决上面的问题,可以使用Java提供的另一个类:java.nio.file.Path。该类通常有以下两种获取方法:

        // 1、通过File获取
        File file = new File("D://testDir/1.txt");
        Path path1 = file.toPath();
        // 2、通过Files工具类直接从路径字符串获取
        Path path2 = Paths.get("D://testDir/1.txt");

 引入了Path类后,代码就简洁许多了,创建目录和文件可以这样写:

        File file = new File("D://testDir/1.txt");
        Path path = file.toPath();
        // 文件所在目录
        Path parentPath = path.getParent();
        // 创建目录,注意:当path相对路径会返回null,需要做下判断
        if (parentPath != null && !"".equals(parentPath.toString())) {
            Files.createDirectories(parentPath);
        }
        // 创建文件
        if (!file.exists()) {
            Files.createFile(path);
        }

 当需要获取文件所在目录和文件名称时,只需这样做:

        // 获取文件所在目录
        String parentPathStr = parentPath.toString();
        // 获取文件名称
        String fileName = path.getFileName().toString();

 还可以文件的目录层数,截取目录:

        int nameCount = path.getNameCount();
        Path subPath = path.subpath(0, nameCount - 1);

2、Files:好用的文件操作工具类

 Files是Path的好搭档,可以帮助我们通过Path方便快捷地操作文件。Files所提供的方法中,大多需要Path类型参数传入。在上面的代码中,已经有了对Files的应用:

File file = new File("D://testDir/test/1.txt");
Path path = file.toPath();
Path parentPath = path.getParent();
// 创建目录
Files.createDirectories(parentPath);
// 创建文件
Files.createFile(path);

 接下来就是关于Files的一些常用的操作文件的便捷方法介绍

1、复制文件

        // 定义一个文件
        File source = new File("D:/testDir/source/1.txt");
        // 获取其path
        Path sourcePath = source.toPath();
        // 获取该path的父目录
        Path parentPath = sourcePath.getParent();
        if (parentPath != null && !"".equals(parentPath.toString())) {
             Files.createDirectories(parentPath);
        }
        // 创建文件
        if (!source.exists()) {
             Files.createFile(sourcePath);
        }
        // 定义复制文件地址
        File target = new File("D:/testDir/target/2.txt");
        Path targetPath = target.toPath();
        // 获取复制文件父目录
        Path targetParentPath = targetPath.getParent();
        if (targetParentPath != null && !"".equals(targetParentPath.toString())) {
            Files.createDirectories(targetParentPath);
        }
        // 复制文件,StandardCopyOption.REPLACE_EXISTING表示当文件存在时覆盖
        Files.copy(sourcePath, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
知识点
1、源文件的目录和地址必须已经存在,目标(复制)文件则目录必须已经创建
2、Files.copy() CopyOption 参数的实现类StandardCopyOption介绍:
(1)StandardCopyOption.REPLACE_EXISTING:若目标文件已创建,覆盖
(2)StandardCopyOption.COPY_ATTRIBUTES:若目标文件已创建,不进行覆盖,会抛出异常
(3)StandardCopyOption.ATOMIC_MOVE:原子地移动文件,会保证多个文件同时成功或失败。该类型不可用于Files.copy()方法,正确用法是在Files.move()中使用,该方法用于移动文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值