igrilkul igrilkul - 2 months ago 16x
Java Question

Switching two lines in a text file in Java

I've been stuck on this for a while and I've finally decided to plead for help.
So I have a small text file and the user wants to switch 2 lines from it, the user enters the indexes of the 2 lines and I have to switch em.
So far my ideas have been to either use replaceALL with 2 regexes
, but A: That probably won't switch them but just end up replacing one with the other, leaving me with a duplicate and B: I have no idea how to locate the nth line using regex;
or use - Files.readAllLines(Paths.get(name)).get(index); to get the two lines but then I'm still struggling with the actual switching process.


You can use

  • Files.readAllLines to get all lines as a list
  • swap the two elements of the list. e.g. Collections.swap
  • write all the lines back out to update the file.

If you need to be able to work with large files you could

  • Use RandomAccessFile to find the start/end of the lines you need by reading from the start of the file.
  • Read the two lines into a buffer.
  • Write the two lines out in place, but swapped around.