简体   繁体   中英

Read in the last n lines of a csv file using a BufferedReader

I have a program that reads in the first and last lines of a CSV file using a BufferedReader and now I need to convert this to read the first and last 8 lines of the file, since the format has changed. But I'm not sure how denote the last 8 lines.

How(can I) would I denote the last 8 lines of a file using a BufferedReader

try(BufferedReader reader = new BufferedReader(
        new InputStreamReader(
                response.getEntity().getContent()))) {

     if(reader != null){
         String aux = "";
         String lastLineMinusOne = "";
         while ((aux = reader.readLine()) != null) {
             String auxTrimmed = aux.replaceAll("(?m)^[ \t]*\r?\n", "");
             if(count == 0)firstLine = auxTrimmed;
             lastLineMinusOne = lastLine;
             lastLine = auxTrimmed;
             count ++;
        }
        logger.info("Count = " + count); 
        columns = firstLine.split(",");

        data = lastLine.split(","); 

just use a Deque and remove them if size goes over 8 .

Since queue is FIFO then if remove() is used it will only keep the most 8 recent entries.

Deque<String> queue=new ArrayDeque<String>();
String line;
while ((aux = reader.readLine()) != null){
  if(queue.size()>=8){
    queue.remove();
  }
  queue.add(aux);
}
System.out.println(queue.size());//should print 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM