0

I'm trying to write a method for a program that only reads the last line of the text file, but I can't find out what the issue is and I have been searching for a while. Any help would be amazing.

public String getLastLine(String path) throws IOException {
    String st;
    String ot = null;
    try {
        File file = new File(path);
        BufferedReader br = new BufferedReader(new FileReader(file));
        while ((st = br.readLine()) != null) {
            ot = st;
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return ot;
    
}

Everything I have been able to find tells me to create a string and set it to null or to set it to "", but this isn't working at all for me. I keep getting this error code

org.junit.ComparisonFailure: expected:<[BZHbzAauZi]> but was:<[]>

I tried to return the last line of a text file but it only returns as a empty space.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Shizzy
  • 1
  • 3
    Could be stating the obvious, but is the last line in the file empty? – Robert Harvey Nov 12 '22 at 20:55
  • Does this answer your question? [Quickly read the last line of a text file?](https://stackoverflow.com/questions/686231/quickly-read-the-last-line-of-a-text-file) – vinsce Nov 12 '22 at 20:56
  • 1
    If the file ends with a newline sequence, the last line is, in fact, the empty string. – VGR Nov 12 '22 at 21:11
  • @VGR - that's not so. A file that contains a total 4 chars "foo\n" certainly ends with a newline, but the last line is not empty. The file has exactly one line, which is non-empty. – access violation Nov 12 '22 at 21:38

1 Answers1

0
while ((st = br.readLine()) != null) 
{
  if(st.isBlank()) {
    continue;
   }
   ot = st;
 }

Will preserve the last-read, non-blank line.

Christoph Dahlen
  • 826
  • 3
  • 15
  • 1
    Thank you so much this worked! Programming makes me feel stupid. I was working on it before you answered and I was thinking of a if statement like that but instead of thinking to use what you wrote I was doing if (st.equals(""). Thanks again that was driving me crazy. – Shizzy Nov 12 '22 at 22:46
  • **On a side:** To do this below Java 11: `if(st.trim().isEmpty()) { continue; }` – DevilsHnd - 退職した Nov 13 '22 at 04:13