Search code examples
spring-batch

Read text file in spring batch upside down


I'm trying to read a file in spring batch upside down and for that I've created a custom reader as shown bellow:

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;
        }
    }
}

is there any other easier way to do this ?


Solution

  • So, if anyone is wondering here is how to read a file upside down in spring batch:

    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;
            }
        }
    }
    

    And then you need to define your custom reader:

    @Bean
    @StepScope
    public UpsideDownItemReader upsideDownItemReader(@Value("#{jobParameters['filePath']}") String filePath) throws IOException {
            return new UpsideDownItemReader(filePath);
        }