The Randomaccessfile class can implement random read and write operations on files.
- The file location pointer of the new Randomaccessfile object is located at the beginning of the file;
- After each read and write operation, the file position pointer will be shifted to read and write the number of bytes;
- The Getpointer () method is used to obtain the absolute position of the current file position pointer from the file header;
- Use the Seek () method to move the file position pointer (the Seek (long Pos) method moves the file position pointer to the absolute position specified by the parameter pos from the file header);
- The length () method returns the bytes of the file (depending on the length of the file and the position pointer, you can tell if the end of the file is read).
To insert a character in a file at the specified location:
public static void Main (string[] args) throws Exception {
Randomaccessfile RAF = new Randomaccessfile (New File ("Test.txt"), "RW");
Raf.seek (7);
StringBuffer sb = new StringBuffer ();
Byte[] B = new BYTE[20];
int Len;
/* Copy the contents of the pointer to SB */
while (len = Raf.read (b))! =-1) {
String str = new string (B,0,len);
Sb.append (str);
}
Raf.seek (7);//Move the pointer to the specified position
Raf.write ("xyz". GetBytes ());//write the character to be inserted
Raf.write (Sb.tostring (). GetBytes ());
Raf.close ();
}
Io--randomaccessfile class