Java Learning Note (35)-Random Read and write files Randomaccessfile

Source: Internet
Author: User
Tags readfile

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.