Unknown model· unknown
from ShareGPT 90K (shared ChatGPT conversations)
how to overwrite a line at any position in the file using RandomAccessFile in Java
- User
how to overwrite a line at any position in the file using RandomAccessFile in Java
- Assistant
To overwrite a line at any position in a file using
RandomAccessFilein Java, you can follow these steps:- Open the file using
RandomAccessFilein "rw" (read-write) mode. - Move the file pointer to the position where you want to overwrite the line using
seek()method. - Write the new line to the file using
writeBytes()method. - If the new line is shorter than the original line, you may need to pad it with spaces to ensure that all of the original line's characters are overwritten.
- Close the
RandomAccessFile.
Here's some sample code that demonstrates how to overwrite a line at position
posin a file:javaimport java.io.RandomAccessFile; public class OverwriteLine { public static void main(String[] args) throws Exception { String filename = "myfile.txt"; int pos = 100; // position to overwrite String newLine = "This is the new line"; RandomAccessFile file = new RandomAccessFile(filename, "rw"); file.seek(pos); file.writeBytes(newLine); // pad with spaces if necessary long fileLength = file.length(); if (fileLength > pos + newLine.length()) { long paddingLength = fileLength - (pos + newLine.length()); String padding = String.format("%" + paddingLength + "s", ""); file.writeBytes(padding); } file.close(); } }In this example, we open the file "myfile.txt" in "rw" mode and set the position to
posusingseek(). We then write the new line to the file usingwriteBytes().Finally, we check if the new line is shorter than the original line, and if so, we pad it with spaces using
String.format()and write the padding to the file usingwriteBytes(). Finally, we close theRandomAccessFile. - Open the file using