Randomaccessfile class
/ * * Randomaccessfile class, Random Read and write files * * Data segmentation to be regular, each segment size is equal, you can set each piece of data to a larger value, enough to exist each segment of the data * */public class Test04 {public static void main (string[] args) throws IOException {//writefile ();ReadFile ();}//write data public static void WriteFile () throws IOException {//Create a Randomaccessfile instance in read-write mode Randomacce Ssfile raf=new Randomaccessfile ("D:\\java\\aaa.txt","RW");Raf. Write("Zhang San". GetBytes());Raf. Write( the);Raf. writeUTF("Welcome to Nanjing network Bo!" ");Raf. Writeint( -);Raf. Writeboolean(true);Raf. Writedouble(12.5);Raf. Write("Zhang San". GetBytes());Raf. Seek( -);Raf. Writeint( -);Raf. Write("John Doe". GetBytes());Raf. Seek( -*1+ -);Raf. Writeint( -);Move the pointer to the fourth student's position and empty out the third student RAF. Seek( -*3); Raf. Write("Zhao Xiao Liu". GetBytes());Raf. Seek( -*3+ -);Raf. Writeint( at);System. out. println("Write file successfully!" ");Raf. Close();}//Read data public static void ReadFile () throws ioexception{Randomaccessfile raf=new Randomaccessfile ("D:\\java\\aaa.txt","RW");String Name=new string (buffer);System. out. println("first 6 bytes:"+name);int Data=raf. Read();System. out. println("7th byte:"+ (char) data);String Welcome=raf. readUTF();System. out. println("8th Byte and After:"+welcome);Raf. Seek( -*3);Byte[] Buffer=new byte[ -];int Num=raf. Read(buffer);System. out. println(num);System. out. println(Arrays. toString(buffer));String Name=new string (buffer,0, num);int Age=raf. ReadInt();System. out. println("The fourth student's information:");System. out. println("Name:"+name+", Age:"+age);System. out. println("Position of current pointer:"+raf. Getfilepointer());Raf. Close();}}
Java Learning Note (35)-Random Read and write files Randomaccessfile