0

I am fairly new to Java and I would like to ask how is it possible to get the last line of a text file using Java? For example, the contents of the text file would be something like:

001,abc,abc@yahoo.com,123456,President

002,xxx,xxx@gmail.com,xxx,Member

What I am trying to get is the userID of the users (eg:001). I already know how to read from a text file normally, but what I need is the last line from the text file so that I can give users incrementing IDs.

user123
  • 13
  • 4
  • Typically you read file line by line till end of file. May be you could share code how you are reading the file, so that it would be possible to advice you an applicable approach in your case. – GiorgosDev May 03 '22 at 07:35
  • @tresf Yes in a way it helps. Many Thanks! – user123 May 03 '22 at 07:43

1 Answers1

0
try (ReversedLinesFileReader reader = new ReversedLinesFileReader(new File("path/to/file.txt"), StandardCharsets.UTF_8)) {
    System.out.println("Last line is: " + reader.readLine());
} catch (IOException e) {
    // ignore for now
}

It should work perfect

  • Just a warning, this solution claims that there may be performance issues for larger files, I'm not sure if these concerns are still relevant: https://stackoverflow.com/questions/8664705/how-to-read-file-from-end-to-start-in-reverse-order-in-java – tresf May 03 '22 at 07:35
  • Yes, it does work! The file I'm working with is fairly small so I think there shouldn't be any problems for now. Many Thanks c: – user123 May 03 '22 at 07:42
  • 1
    Please specify the library that contains `ReversedLinesFileReader`, as this is not something in the standard Java API. – Mark Rotteveel May 03 '22 at 07:47