日期:2014-05-16  浏览次数:21037 次

RandomAccessFile类的简单介绍,以及代码演示

RandomAccessFile类,支持对文件的读取和写入。并且可以设置写入和读取的位置。该位置主要是以字节体现。相当于该文件存储在一个大型byte[] 数组。隐含存在一个指向该数组的指针。类似于该类对象可以设置该隐含的指针位置进行对文件从任意位置开始读写。

RandomAccessFile类的构造方法。

RandomAccessFile(String name,String mode);//name 为与该类对象关联的文件名。mode为打开文件的访问模式。

RandomAccessFile(File file,String mode);//file为相关联的文件。mode同上。mode主要有一下四个值:

含意

"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException
"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
"rwd"  打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。

主要方法:

void write(byte[] b);将b.length个字节写入到文件的指定位置中去。

void write(int b);//向文件写入指定的字节。该方法只写如最低的八位。如 write(97) 和write(609)写入的内容一样。都是97 字母a。

void writeInt(int b);//按四个字节将int写入到文件中去。先写高位。

int read();//从文件中读取一个数据字节。

int read(byte[] b);//将最多b.length个数据字节从文件中读到改字节数组中去。

int readInt();//从文件中读取一个有符号的32位整数。

void seek(long pos);//设置文件读写的隐含指针位置偏移量。

long getFilePointer();返回文件中的当前偏移量。

void close();//关闭此随机访问文件流并释放与该流关联的所有系统资源。

代码演示:

package RandromAccessDemo;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {		
//		write();
//		read();
		randomWriter();
	}

	public static void randomWriter() throws IOException {
		/*
		 * 可以再多线程中进行对同一个文件进行写入。
		 */
		RandomAccessFile raf = new RandomAccessFile("Random.txt","rw");
//		raf.seek(3*8);//设置指针位置
		raf.write("武松".getBytes());
		raf.writeInt(103);
	}

	public static void read() throws IOException {
		RandomAccessFile raf = new RandomAccessFile("Random.txt","r");
		raf.seek(1*8);
		
		byte []buf = new byte[4];
		raf.read(buf); 
		String name = new String(buf);
		int age = raf.readInt();
		System.out.println("name :"+name+"  age : "+age);
		System.out.println("getFilePointer: "+raf.getFilePointer());//获得当前指针位置。
		
		raf.close();
		
	}

	public static void write() throws  IOException {
		/*
		 * 当文件存在时,不创建,从指定位置开始写。当文件不存在时,则创建文件.
		 */
		RandomAccessFile raf = new RandomAccessFile("Random.txt","rw");
		raf.write("旺财".getBytes());
//		raf.write( 97);//a write只写最低八位
//		raf.write(609);//a
		raf.writeInt(97);
		raf.write("李煜".getBytes());
		raf.writeInt(99);
		
		raf.close();
	}

}