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