上百万行json查询

场景描述:

上百万条数据直接读取可能会导致内存溢出,这里先把数据存成一个文件,然后转换成流去处理,一行一行读取数据,我下面代码实现读一个文件,文件行数400万行,文件的每一行都是一个json串,获取属性num=43的json串,整个文件读完需要3秒左右,并且对内存的消耗不会太大(还没测试对比)。

// pom.xml引入
<dependency>  
	<groupId>com.fasterxml.jackson.core</groupId>  
	<artifactId>jackson-databind</artifactId>  
	<version>2.13.1</version>
</dependency>

**

package com.dhrs.base.stream;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Optional;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonAttributeFinder {
    private static final String FILE_PATH = "E:/临时/file.txt";  // 文件路径
    private static final String TARGET_ATTRIBUTE = "num";  // 属性名称
    private static final int TARGET_VALUE = 43; // 你要找的数字

    public static void main(String[] args) {
        Long l1 = System.currentTimeMillis();
        Optional<String> result = findJsonValue(FILE_PATH, TARGET_ATTRIBUTE, TARGET_VALUE);
        Long l2 = System.currentTimeMillis();
        System.out.println(l2-l1);
        if (result.isPresent()) {
            System.out.println("找到了! JSON字符串: " + result.get());
        } else {
            System.out.println("未找到符合条件的JSON字符串.");
        }
    }

    private static Optional<String> findJsonValue(String filePath, String targetAttribute, int targetValue) {
        ObjectMapper objectMapper = new ObjectMapper();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                JsonNode jsonNode = objectMapper.readTree(line);
                if (jsonNode.has(targetAttribute) && jsonNode.get(targetAttribute).intValue() == targetValue) {
                    return Optional.of(line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Optional.empty();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值