I need to swap the position of two lines in a file accessing directly to them.
All the lines in my file have the same size in bytes, I know where every line is since they are all the same size, but I need to point to them directly without going through all the file.
So I need to know how to position myself there and how to read and delete them, and I really couldn't find a solution I understand.
Thanks in advance.
Example: I want to swap the second and fourth line.
File content:
1;first line ; 1
2;second line ; 1
3;third ; 2
4;fourth ; 2
5;fifth ; 2
How it should look:
1;first line ; 1
4;fourth ; 2
3;third ; 2
2;second line ; 1
5;fifth ; 2
Purely educational example. Don't use something like that in production. Use a library instead. Anyway, follow my comments.
File example
ciaocio=1
edoardo=2
lolloee=3
Target
ciaocio=1
lolloee=3
edoardo=2
final int lineSeparatorLength = System.getProperty("line.separator").getBytes().length;
// 9 = line length in bytes without separator
final int lineLength = 9 + lineSeparatorLength;
try (final RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
// Position the cursor at the beginning of the first line to swap
raf.seek(lineLength);
// Read the first line to swap
final byte[] firstLine = new byte[lineLength];
raf.read(firstLine);
// Position the cursor at the beginning of the second line
raf.seek(lineLength * 2);
// Read second line
final byte[] secondLine = new byte[lineLength];
raf.read(secondLine);
// Move the cursor back to the first line
// and override with the second line
raf.seek(lineLength);
raf.write(secondLine);
// Move the cursor to the second line
// and override with the first
raf.seek(lineLength * 2);
raf.write(firstLine);
}