Randomaccessfile Flow Summary

Source: Internet
Author: User
Tags readline

Randomaccessfile is the most versatile file content in the Java input/output stream architecture

Access the class.

Inheritance Relationship: Java.lang.object-->java.io.randomaccessfile

A summary point:

1 You can read the contents of a file or output data to a file

2 Unlike normal input/output streams, Randomaccessfile supports " random

Access , the program can jump directly to the file anywhere to read and write data. Here " with

The meaning of "machine access " is the freedom to access files anywhere (with InputStream,

Reader streams need to be read backwards or written out differently).

3 because Randomaccessfile can freely access any location of the file,

If you want to access only part of the file, instead of reading the file from the beginning to the end, make

It is a good choice to use Randomaccessfile.

4 when Randomaccessfile is used as an output stream, the Randomaccessfile

Allows free positioning of file record pointers, so randomaccessfile can not start from

Place to start the output, that is, Randomaccessfile can append to the existing file

Content. If your program needs to append content to an existing file, you should use the

Randomaccessfile.

The construction method of two Randomaccessfile

1 randomaccessfile (file file, String mode)

2 Randomaccessfile (string name, string mode)

Three common methods

1 Randomaccessfile provides two ways to manipulate file record pointers

* Long Getfilepointer (): Returns the current position of the file record pointer

* Void Seek (long pos): Position the file record pointer to the POS location

2 read/write method to view API documentation.

Four examples

Example 1

/*

The function of this program:

Use the Randomaccessfile stream to read part of the data that the stream is associated to a file, rather than read

Take the entire file

*/

Import java.io.*;

public class Randomaccessfiletest

{

public static void Main (String [] args)

{

Randomaccessfile RAF = null;

Try

{

Create an arbitrary access file stream Randomaccessfile in read-only mode, associated to the hard disk

On a file

Raf

=

New

Randomaccessfile ("D:\\fengkuang_java_ligang\\15\\15-7\\randomaccessfiletest.java", "

R ");

Gets the position of the file pointer for the Randomaccessfile object, where the initial position is 0

System.out.println ("Randomaccessfile's file pointer position is:" +

Raf.getfilepointer ());

Move the RAF file to record the position of the pointer

Raf.seek (700);

byte[] buff = new byte[1024];

The number of bytes used to hold the actual read

int hasread = 0;

while ((Hasread = Raf.read (buff)) > 0)

{

Converts the data in a byte array into a string and outputs

System.out.println (New String (Buff,0,hasread));

}

}

catch (IOException ex)

{

Ex.printstacktrace ();

}

Finally

{

Try

{

if (null! = RAF)

{

Raf.close ();

}

}

catch (IOException E)

{

E.printstacktrace ();

}

}

}

}

===============================================================

Example 2

/*

The function of this program:

Append content to the file associated with the Randomaccessfile flow

In order to append content, the program should first move the file record pointer of the stream to the file's

And then start outputting the content to the file

*/

Import java.io.*;

public class Appendcontent

{

public static void Main (String [] args)

{

Randomaccessfile RAF = null;

Try

{

Opens a Randomaccessfile stream object as read and write, associated to the hard disk

On the file

Raf

=

New

Randomaccessfile ("d:\\fengkuang_java_ligang\\15\\15-7\\ use Randomaccessfile

Append content to the document "," RW ");

Raf.length () Statement: Measures the length of the file to which the stream is associated, in bytes.

and returns the length

Raf.seek () sets the position of the file record pointer for the stream at the next read, write

Operation, it starts at that position

This moves the file record pointer to the end of the file to which the stream is associated.

Raf.seek (Raf.length ());

Raf.write ("Append the content! \ r \ n ". GetBytes ());

}

catch (IOException E)

{

E.printstacktrace ();

}

Finally

{

Try

{

if (RAF! = NULL)

{

Raf.close ();

}

}

catch (IOException ex)

{

Ex.printstacktrace ();

}

}

}

}

============================================================

Example 3

/*

The function of this program:

Use the Randomaccessfile stream to implement the ability to insert content into a specified file, at a specified location

Implementation steps:

1 First read the contents of the file after the insertion point into the temporary file

2 reposition the file record pointer to the insertion point

3 Write the content you want to insert from the location of the insertion point to the file

4 appends the contents of the temporary file to the back of the file, which is appended to the inserted content.

Behind

*/

Import java.io.*;

public class Insertcontent

{

public static void Insert (String filename,long pos,string insercontent) throws

Exception

{

Randomaccessfile RAF = null;

Create a temporary file to hold the data after the insertion point

File tmp = file.createtempfile ("tmp", NULL);

FileInputStream tmpin = null;

FileOutputStream tmpout = null;

Tmp.deleteonexit ();

Try

{

Open Randomaccessfile Stream in read and write mode

RAF = new Randomaccessfile (filename, "RW");

Create an input-output file stream that is associated to a temporary file

Tmpout = new FileOutputStream (TMP);

Tmpin = new FileInputStream (TMP);

Position the file record pointer of the stream to the insertion point

Raf.seek (POS);

--------The following code to read the contents of the insertion point into a temporary file to be saved---------

byte [] buff = new byte[1024];

int hasread = 0;

To read the data behind the insertion point using a looping method

while ((Hasread = Raf.read (buff)) > 0)

{

Writes the data behind the insertion point to a temporary file

Tmpout.write (Buff,0,hasread);

}

----------The following code to insert the content----------

Reposition the file record pointer for the stream to the POS location

Raf.seek (POS);

Append the content you want to insert

Raf.write (Insercontent.getbytes ());

----------The following code appends the data to the end of the insertion point in the original file

----------

while ((Hasread = Tmpin.read (buff)) > 0)

{

Raf.write (Buff,0,hasread);

}

}

Finally

{

if (null! = RAF)

{

Try

{

Raf.close ();

}

catch (Exception e)

{

E.printstacktrace ();

}

}

}

}

public static void Main (String [] args) throws Exception

{

Insert ("source file. txt", 45, "inserted content \ r \ n");

}

}

============================================================

Example 4

/*

This program features:

Using Randomaccessfile flow and BufferedReader to complete the input from the keyboard

Data

and writes the data to a file on the hard disk without overwriting the original number on the file

Recording keyboard input at the same time

Finally, the content on the file is output to the monitor.

*/

Import java.io.*;

Import java.util.*;

public class Randomaccessfile2test

{

Modified to be static because the static main () method is used in the

static BufferedReader br = NULL;

static Randomaccessfile RAF = NULL;

static BufferedReader Br2 = null;

public static void Main (String [] args) throws Exception//This program is temporarily not located

Abnormal

{

/*

*/

Step 1: First use the conversion stream InputStreamReader to get the input characters from the keyboard

String

String str;

reading data from the keyboard

System.in represents the keyboard input, and executing the statement will get a InputStream object

Builder InputStreamReader (InputStream in), InputStreamReader

Attached to InputStream

After you execute new InputStreamReader (system.in), you get a link to the keyboard

Stream, but the stream does not have a buffer, and each reading of a keyboard data starts the converter for conversion,

Efficiency is not high.

To improve the efficiency of conversion, set a bufferedreader outside the InputStreamReader

Buffered streams, each read of the keyboard data is placed in the buffer, and then converted all at once.

Does that make sense??

br = new BufferedReader (new InputStreamReader (system.in));

str = br.readline () reads data entered from the keyboard

while (null! = (str = br.readline ()))//reads the input data from the keyboard straight

Enter exit to end the loop

{

if (Str.equalsignorecase ("Exit"))//Determine if the input content equals exit

Break

/*

Step 2: Use the Randomaccessfile stream to write the data entered from the keyboard

To a file on a hard disk

The data is appended to the file using the Randomaccessfile stream, making

The original data on the file is not overwritten

*/

Opens a Randomaccessfile stream object as read and write, associated to the hard disk

On the file

Raf

=

New

Randomaccessfile ("d:\\fengkuang_java_ligang\\15\\15-7\\ every time the input from the keyboard

"," RW ");

This moves the file record pointer to the end of the file to which the stream is associated.

Raf.seek (Raf.length ());

Create a Calendar object

Calendar C = calendar.getinstance ();

C.gettime () Gets the Date object that represents the current time

ToString () returns the string representation of the current time

Get the current time

String strtime = C.gettime (). toString ();

Writes the current time to the file, that is, the time to enter data from the keyboard

Raf.write (Strtime.getbytes ());

Raf.write (":". GetBytes ());

Append data entered from the keyboard to the end of the file

Raf.write (Str.getbytes ());

Write line break

Raf.write ("\ r \ n". GetBytes ());

/*

Step 3: Use BufferedReader to read the files on the hard drive and

Content output of the piece

*/

Create a BufferedReader buffered stream that is associated to a file on your hard disk

Br2

=

New

BufferedReader (New

FileReader ("D:\\fengkuang_java_ligang\\15\\15-7\\ each time you enter content from the keyboard");

String str2;

System.out.println (The contents of the------file are as follows---------");

Read file contents in a circular fashion

while (null! = (str2 = Br2.readline ()))

{

System.out.println (STR2);

}

SYSTEM.OUT.PRINTLN ("------The contents of the document as above---------");

}

Br.close ();

Raf.close ();

Br2.close ();

}

}

2016-03-29

Randomaccessfile Flow Summary

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.