Java Core Programming--file Random read-write class (Randomaccessfile)

Source: Internet
Author: User

1.RandomAccessFile

Randomaccessfile primarily for read and write access to file content

2. Access mode

"R": Read-only mode.

"RW": Opens for Read and access and creates a file if the file does not exist.

"RWS": Written in addition to the ' RW ' feature, file contents or metadata updates.

"RWD": In addition to the ' RW ' feature, the file content is written together when it is updated.

3. Use Cases

 Packagetest;ImportJava.io.File;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.RandomAccessFile; Public classrandomaccess { Public Static voidMain (string[] args) {Try{File File=NewFile ("C:\\img\\666.txt"); //Open FileRandomaccessfile randomaccess =NewRandomaccessfile (file, "RWD");//Accessing FilesLong lenth = Randomaccess.length ();//Get file lengthSystem.out.println ("Lenth:" +lenth); Randomaccess.seek (4);//Set pointer position//Read File            intc = Randomaccess.read ();//read one byteSystem.out.println ("C:" +c); System.out.println ("C:" + (Char) c);//Convert to character                        byte[] B =New byte[3];//reading byte numbers, creating arraysRandomaccess.read (b, 1, 2);//read two bytes from pointer 1 write to array bString s =NewString (b);//Convert to StringSystem.out.println ("byte:" +s);//Output//Write FileFile file2 =NewFile ("C:\\img\\777.txt"); if(!File2.getparentfile (). exists ())            {File2.getparentfile (). Mkdirs ();            } file2.createnewfile (); Randomaccessfile RandomAccess2=NewRandomaccessfile (File2, "RWD");//Accessing FilesRandomaccess2.write (b);//Write character Array//Close FileRandomaccess.close ();                    Randomaccess2.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                    }}

Java Core Programming--file Random read-write class (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.