簡體   English   中英

如何在Item閱讀器中獲取spring批處理文件中的行數

[英]How to get number of lines in a file in spring batch in Item reader

我是Spring的新手。 我有一個Job,它讀取文件並寫入數據庫。 如果文件中的記錄數超過8000,我不應該處理該文件,並且應該停止作業執行。 請建議更好的方法是什么。

您可以在itemreader上實現StepExecutionListener。 然后,您可以獲得與您的行號對應的readcount。

 public class ExampleItemReader implements ItemReader<String>, StepExecutionListener {

    public synchronized String read() throws Exception {
        return "";
    }

    @Override
    public ExitStatus afterStep(StepExecution executionContext) {
        if (executionContext.getReadCount() > 8000) {
            return ExitStatus.COMPLETED;
        }
        return ExitStatus.EXECUTING;
    }

    @Override
    public void beforeStep(StepExecution arg0) {

    }

}

建議閱讀春季批量模式

不是特定於spring的東西,但java.io有一個類LineNumberReader 您可以使用它及其skip方法來跳過大量的字符。

例:

public int getNoOfLines(String fileName) {
   LineNumberReader reader = new LineNumberReader(new FileReader(fileName));
   reader.skip(Integer.MAX_VALUE); //skips those many chars, if you feel your file size may exceed you can use Long.MAX_VALUE
   return reader.getLineNumber();
}

這比僅讀取文件和計數更有效。

我假設你文件中的記錄不是固定長度。 如果是這樣,File.length()將很容易計算文件中的記錄數。

如果不是,它需要精確到8000還是大約8000? 如果這是一個粗略的限制,我會獲得這些文件的平均記錄長度,然后使用File.length()來估計記錄的數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM