java提供了一个可以对文件随机访问的操作,访问包括读(r)和写(rw)操作。该类名为RandomAccessFile。
该类的读写是基于指针的操作。
常用方法:
void write(int d)
该方法会根据当前指针所在位置处写一个字节,是将参数int的低8位写出。
int read()
该方法会从文件中读取一个byte(8位)填充到int的低8位,高24位位0,返回值范围正数:0~255,返回-1表示读到文件末尾。每次读取后自动移动文件指针,准备下次读取。
void write(byte[] d)
根据当前指针所在位置处连续写出给定数组中的所有字节。
void write(byte[] dt,int offSet, int len)
根据当前指针所在位置处连续写出给定数组中的部分字节。从数组中offSet开始了连续len个字节。
int read(byte[] d)
从指针位置处尝试最多读取给定数组的总长度的字节量,并从给定字节数组第一个位置开始,将读取到的字节顺序存放至数组中,返回值为实际读取到的字节量。
void close()
RandomAccessFile在对文件访问的操作全部结束后,要调用close方法来释放与其关联的所有系统资源。
文件指针操作方法:
long getFilePointer
该方法用于获取当前RandomAccessFile的指针位置。
void seek(long pos)
用于移动当前RandomAccessFile的指针位置。
int skipBytes(int n)
尝试跳过输入的n个字节以丢弃跳过的字节。
该方法可能跳过一些较少数量的字节(可能包括0)。这可能由任意数量条件引起;在跳过n个字节前,已到达文件的末尾是一种可能。
此方法不抛出EOFException。返回跳过的实际字节数。如果n为负数则不跳过任何字节。
package myfile;
import java.io.RandomAccessFile;
/**
* 测试写出方法
* @author Whh
*
*/
public class TestRandomAccessFile {
public static void main(String[] args) throws Exception {
testWrite();
testRead();
System.out.println("***********************************");
testWriteByteArray();
testReadByteArray();
System.out.println("***********************************");
testPointer();
}
/**测试写出方法**/
public static void testWrite() throws Exception{
RandomAccessFile raf = new RandomAccessFile("raf.text", "rw");
//写出一个字节,写出的是int值得低8位
System.out.println("指针位置:"+raf.getFilePointer());
raf.write(2);
raf.close();
}
/**测试读取方法**/
public static void testRead() throws Exception{
RandomAccessFile raf = new RandomAccessFile("raf.text", "r");
int d = raf.read();
System.out.println(d);
System.out.println("指针位置:"+raf.getFilePointer());
raf.close();
}
/**测试批量写出**/
public static void testWriteByteArray() throws Exception{
RandomAccessFile raf = new RandomAccessFile("raf.text", "rw");
//将字符串按默认编码转化为字节
System.out.println("指针位置:"+raf.getFilePointer());
byte[] buf = "Hello world".getBytes();
//将字节数组中所有字节一次性写出
raf.write(buf);
raf.close();
}
/**测试批量读取**/
public static void testReadByteArray() throws Exception{
RandomAccessFile raf = new RandomAccessFile("raf.text", "r");
//创建长度为11的字节数组
byte[] buf = new byte [11];
//尝试读取十个字节存入数组,返回值为读取的字节量
int len = raf.read(buf);
System.out.println("从当前指针开始读取到了:"+len+"个字节");
System.out.println(new String(buf));
System.out.println("指针位置:"+raf.getFilePointer());
raf.close();
}
/**测试指针相关方法**/
public static void testPointer() throws Exception{
RandomAccessFile raf = new RandomAccessFile("raf.text", "r");
//输出指针位置,默认从零开始(文件的第一个字节位置)
System.out.println("指针位置:"+raf.getFilePointer());
//将指针动到位置6,读取world5个字节
raf.seek(6);//将指针位置设为6,下一次操作指针将从位置7开始
System.out.println("指针位置:"+raf.getFilePointer());
byte [] buf = new byte[5];
raf.read(buf);
System.out.println(new String(buf));
System.out.println("指针位置:"+raf.getFilePointer());
raf.close();
}
}