Given some text lines in one string, each line is separated by ‘\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines.
Sol 1:
Take a queue of size 10 and inserting each line in it.
and if lines are more than 10 insert 11th and delete 1 in queue.
and when last n occur print the strings from the queue.
Queue<String> lines = new Queue<String>();
for(String tmp; (tmp = br.readLine()) != null;) {
if (lines.size() >= 10)
lines.remove();
lines.add(tmp);
}
Sol 2:
Sol 1:
Take a queue of size 10 and inserting each line in it.
and if lines are more than 10 insert 11th and delete 1 in queue.
and when last n occur print the strings from the queue.
Queue<String> lines = new Queue<String>();
for(String tmp; (tmp = br.readLine()) != null;) {
if (lines.size() >= 10)
lines.remove();
lines.add(tmp);
}
Sol 2:
public String[] lastNLines(String fileName) throws IOException {
BufferedReader bufferReader = null;
String[] lines = new String[10];
try {
bufferReader = new BufferedReader(new FileReader(fileName));
int count = 0;
String line = null;
while ((line = bufferReader.readLine()) != null) {
lines[count % lines.length] = line;
count++;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bufferReader != null)
bufferReader.close();
}
return lines;
}
No comments:
Post a Comment