在 Spring Batch 中倒置读取文本文件

问题描述 投票:0回答:1

我正在尝试颠倒地读取 spring 批处理中的文件,为此我创建了一个自定义阅读器,如下所示:

import org.springframework.batch.item.ItemReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UpsideDownItemReader implements ItemReader<String> {

    private BufferedReader bufferedReader;
    private List<String> lines;

    public UpsideDownItemReader(String filePath) throws IOException {
        bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filePath)));
        initializeLines();
    }

    private void initializeLines() throws IOException {
        lines = new ArrayList<>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        Collections.reverse(lines);
    }

    @Override
    public String read() throws Exception {
        if (!lines.isEmpty()) {
            return lines.remove(0);
        } else {
            bufferedReader.close();
            return null;
        }
    }
}

还有其他更简单的方法吗?

spring-batch
1个回答
0
投票

所以,如果有人想知道如何在 spring 批处理中颠倒读取文件:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;

import org.springframework.batch.item.ItemReader;

public class UpsideDownItemReader implements ItemReader<String> {

    private BufferedReader bufferedReader;
    private Stack<String> lines;

    public UpsideDownItemReader(String filePath) throws IOException {
        bufferedReader = new BufferedReader(new FileReader(filePath));
        initializeLines();
    }

    private void initializeLines() throws IOException {
        lines = new Stack<>();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            lines.push(line);
        }
    }

    @Override
    public String read() throws Exception {
        if (!lines.isEmpty()) {
            return lines.pop();
        } else {
            bufferedReader.close();
            return null;
        }
    }
}

然后您需要定义您的自定义阅读器:

@Bean
@StepScope
public UpsideDownItemReader upsideDownItemReader(@Value("#{jobParameters['filePath']}") String filePath) throws IOException {
        return new UpsideDownItemReader(filePath);
    }
© www.soinside.com 2019 - 2024. All rights reserved.