java 使用RandomAccessFile类基于指针方式读写文件

java API中提供了一个基于指针操作实现对文件随机访问操作的类,该类就是RandomAccessFile类,该类不同于其他很多基于流方式读写文件的类。它直接继承自Object。

public class RandomAccessFile extends Objectimplements DataOutput, DataInput, Closeable{...}
1.使用该类时可以指定对要操作文件的读写模式。

第一种模式是只读模式,第二种模式是读写模式。在创建该类实例时指定。

@Test
	public void test01() throws IOException{
		//读写模式
		RandomAccessFile  r=new RandomAccessFile(new File(""),"rw" );
		//只读模式
		//RandomAccessFile  r=new RandomAccessFile(new File(""),"r" );

		r.write(1);//写出一个字节,写出的是int值的低8位
		r.close();
		r.read();//每次读一个字节,填充到int的低八位
	}
2.字节读取操作

(1)void write(int d):写出该int值的低8位,其他位舍弃

@Test
	public void testWrite() throws IOException{
		RandomAccessFile file=new RandomAccessFile(new File("emp.txt"),"rw");
		file.write(97);//0110 0001
		file.write(98);//0110 0010
		file.write(99);//0110 0011
	}
(2)int read():注意:该方法只会从文件中当前指针处读取一个byte(8位)的数据填充到int返回值的第八位,其他位用0填充。若该方法返回0,则代表读到文件末尾。
以上两种方法使用起来当然会很麻烦。

RandomAccessFile类中还封装了对8中基本数据类型的读写操作,使用起来会很方便。

分别为

readByte(),  readShort(),  readInt(),  readLong(), readFloat(),readDouble(),readBoolean(),readChar()

返回值类型均为对应的基本数据类型。同时相应的也有这八中writeByte()...方法。这是在流式读写文件中所不具有的。

3.文件指针操作

RandomAccessFile类的所有读写操作均是基于指针的,指针会随着读或写的操作往后移动。同时也可以通过方法自由的操作指针的位置,以此更方便的读写文件。

常用方法

(1)long getFilePointer():该方法用于返回当前指针位置。默认读写操作时,指针的初始位置为文件的第一个字节处,即值为0

(2)void seek(long pos):该方法可以设定指针位置

(3)int skipBytes(int n):该方法可以跳过n个字节

/**
 * RandomAccessFile:基于指针读写,总是在指针当前位置读写,无论读写,指针都会向后移动
 * RandomAccessFile总是在指针当前位置进行读写字节,并且无论进行了读还是写一个字节后,
 * 指针都会自动向后移动到下一个字节的位置
 * 默认创建出来RandomAccessFile时,指针位置为0,即:文件的第一个字节的位置
 * @author zc
 */
public class T13RandomAccessFile {
	public static void main(String[] args) throws IOException {
		RandomAccessFile raf=new RandomAccessFile(new File("emp.txt"),"rw");
		int a=255;
		//虽然能写入,但是在记事本中打开仍是乱码字符
		raf.write(a>>>24);//11111111
		raf.write(a>>>16);
		raf.write(a>>>8);
		raf.write(a);
		//获取当前指针位置
		long pos=raf.getFilePointer();
		//!!注意,返回值是字节4,前面写入的四个字节对应从0--3字节
		System.out.println("pos:"+pos);//4
		
		//将int值分成四部分,写入
		raf.writeInt(255);
		System.out.println("pos:"+raf.getFilePointer());//8
		
		raf.writeLong(255);//long八个字节
		System.out.println("pos:"+raf.getFilePointer());//16
		
		raf.writeFloat(8);//float四个字节
		System.out.println("pos:"+raf.getFilePointer());//20
		
		raf.writeDouble(12.1);//double八个字节
		System.out.println("pos:"+raf.getFilePointer());//28
		
		raf.write(new byte[]{1,1});
		
		raf.writeBoolean(false);
		
		raf.writeChar(1);
		
		//此时已经写完,指针指向文件某位
		System.out.println(raf.read());//-1
		
		/*
		 *void seek(long pos)
		 *将指针移动到指定位置 
		 * */
		raf.seek(0);
		System.out.println("point:"+raf.getFilePointer());//0
		
		//读取刚刚写入的long值
		raf.seek(8);
		long l=raf.readLong();
		System.out.println("读出的long值:"+l);//255
		//读取刚刚写入的double值
		raf.seek(20);
		System.out.println(raf.readDouble());//12.1
		raf.close();
	}
}







你可能感兴趣的:(JavaSE)