快速读写文本文件

package com.example.demo.java;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * @author CQO
 * @since 2023/03/15 14:18
 */
public class ReadFileTest {

    public static void main(String[] args) throws URISyntaxException, IOException {

        // 如何快速将文本读取为字符串
        // 需求示例: 将resources/templates/test.json读取并转为map
        URL resource = ReadFileTest.class.getClassLoader().getResource("templates/test.json");
        if (resource != null) {
            URI uri = resource.toURI();
            Path path = Paths.get(uri);
            byte[] bytes = Files.readAllBytes(path);
            String s = new String(bytes);
            JSONObject jsonObject = JSON.parseObject(s);
            System.out.println(jsonObject);
            System.out.println(s);
        }

        // 将Map对象转为json字符串并写入文本文件中
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "ChenQ");
        map.put("age", 28);
        String string = JSON.toJSONString(map);

        Path path = Paths.get("a.json");
        Files.write(path, string.getBytes(StandardCharsets.UTF_8));


        // 如果你需要逐行读取文件
        String s2 = Files.lines(Paths.get(resource.toURI())).collect(Collectors. joining("__"));
        System.out.println(s2);

//        // 如果使用JDK11以上的版本
//        String s1 = Files.readString(Paths.get(resource.toURIO()));
//        Files.writeString(Paths.get( "b.txt"),s1);

    }

}

posted @ 2023-03-15 16:00  unknown-n2  阅读(14)  评论(0编辑  收藏  举报