[英]Count number of lines in a string in java - BufferedReader behavior
[英]How to count a fixed no of lines in a large file using bufferedreader in java
我需要讀取一個包含幾百萬行的大文件。 現在,當我讀取整個文件時,緩沖區變得很重,有時會拋出內存異常。
所以我想要的是,例如,我有10000行。 我想讀取直至1000行,對其進行處理,然后再次從1001讀取至2000,依此類推直至結束。 任何幫助將不勝感激。
我現在所要做的
String filePath="some path";
log.debug("File name got for promo :::::: "+filePath);
File f = new File(filePath);
int i = 0;
try {
System.out.println("Reading the file for data:::::: ");
BufferedReader br = new BufferedReader(new FileReader(f));
String aLine = null;
Runtime.getRuntime().freeMemory();
while ((aLine = br.readLine()) != null) {
System.out.println(aLine);
if(aLine.trim().length()!=12)
{
System.out.println("Not a Valid number at line --->"+(i+1));
continue;
}
//numberList.add(aLine.trim());
i++;
}
Runtime.getRuntime().freeMemory();
log.debug("Total Number/Row found in the file is --> " + i);
}
不要將所有行存儲在List
或任何其他結構中,而要即時對其進行處理 。
例如,在您的情況下:
int nRows = 0;
int numbers = 0;
while ((aLine = br.readLine()) != null) {
if(aLine.trim().length() == 12) {
numbers++;
}
nRows++;
}
log.debug("Total number of rows: " + nRows);
log.debug("Total number of line of length 12: " + numbers);
您可以考慮通過FileChannel使用內存映射文件,也可以使用java.nio包,而不是使用固定緩沖區方法,這些包據說比java.io快,
這是鏈接到文章的文章,其中介紹了兩種方法,固定緩沖區方法和帶有nio的內存映射文件:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.