The Randomaccessfile class is a Java class that can read and write randomly, and can dynamically move pointers for Random writes
Constructor information:
Main method: If you write on the position where the Seek method is set, the content on the current year's location will be overwritten
Package Cn.bean.demo.random;import Java.io.ioexception;import Java.io.randomaccessfile;public class randomaccessfiletest {public static void main (string[] args) {testrandomreadwrite ();} static void Testrandomreadwrite () {//Create a random read-write instance [RW stands for Read and write, R for read-only, cannot write]try (randomaccessfile accessfile=new Randomaccessfile ("String1.txt", "RW");) {//Insert a Hello china//in the second line of the file to read the first line of content and move the pointer to the end of the first line string line= Accessfile.readline ();//Read the rest of the content into a buffer [if the contents of the file is too large for memory consumption, the remaining content should be written to a disk file, so it is best to determine the size of the file when randomly inserted, in processing]byte[] Buff=new byte[(int) (Accessfile.length ()-line.length ())];//reads the remaining content into the buff accessfile.read (buff);//After reading the pointer at the end of the file, Move the pointer position before inserting Accessfile.seek (Line.length ());//Insert Hello Chinaaccessfile.writebytes ("\nhello china\n");} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Random Read and write Randomaccessfile