If you only need to keep track of one previous line, you can do something like the following, keeping track of the previous line through each iteration (I assumed you were using a reader; for this example, BufferedReader
):
String previous = null, line; // null means no previous line
while (line = yourReader.readLine()) {
// Do whatever with line
// If you need the previous line, use:
if (yourCondition) {
if (previous != null) {
// Do whatever with previous
} else {
// No previous line
}
}
previous = line;
}
If you need to keep track of more than one previous line, you may have to expand that into an array, but you will be keeping a huge amount in memory if your file is large--as much as if you'd read the entire file, once you get to the last line.
There is no simple way in Java or Android to read the previous line, only the next (as it is easier in file I/O to more forward than backward).
One alternative I can think of is to keep a line marker (starting at 0), and as you advance through the lines, increase it. Then, to go backwards, you have to read the file line by line again, until you get to that line minus one. If you need to go backwards, go to that new line minus one, and so on. It would be a heavy operation, most likely, but would suit your needs.
Edit: If nothing above will work, there is also a method to read in a file backwards, in which you may be able to use to find the previous line by iterating forward. Just an alternative idea, but definitely not an easy one to implement.