/**
*
*/
package de.tutorials;
import java.io.RandomAccessFile;
/**
* @author Thomas.Darimont
*
*/
public class DeleteFirstLinesExample {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
RandomAccessFile randomAccessFile = new RandomAccessFile("lines.txt",
"rw");
int numberOfLinesToBeSkipped = 5;
for (int i = 0; i < numberOfLinesToBeSkipped; i++) {
System.out.println("Skipping: " + randomAccessFile.readLine());
}
long sourcePosition = randomAccessFile.getFilePointer();
long destinationPosition = 0;
byte[] buffer = new byte[65535];
long originalLengthInBytes = randomAccessFile.length();
moveContent(randomAccessFile, sourcePosition, destinationPosition,
originalLengthInBytes - sourcePosition,buffer);
randomAccessFile.setLength(originalLengthInBytes - sourcePosition);
randomAccessFile.close();
}
private static void moveContent(RandomAccessFile randomAccessFile,
long sourcePosition, long destinationPosition, long lengthInBytes, byte[] buffer)
throws Exception {
int currentByteCount = 0;
int bytesRead = 0;
int bytesWritten = 0;
long currentSourcePosition = sourcePosition;
long currentDestinationPosition = destinationPosition;
randomAccessFile.seek(currentSourcePosition);
do {
randomAccessFile.seek(currentSourcePosition);
currentByteCount = randomAccessFile.read(buffer);
bytesRead += currentByteCount;
if (bytesRead > lengthInBytes) {
currentByteCount = ((int) lengthInBytes) - bytesWritten;
}
bytesWritten += currentByteCount;
randomAccessFile.seek(currentDestinationPosition);
randomAccessFile.write(buffer, 0, currentByteCount);
currentSourcePosition += currentByteCount;
currentDestinationPosition += currentByteCount;
randomAccessFile.seek(currentSourcePosition);
} while (bytesWritten < lengthInBytes);
}
}