RandomAccessFile——文件操作
1.创建对象
1.1RandomAccessFile是可以对文件进行随机访问的操作,包括读操作和写操作,该类是基于指针的操作。
1.2只读模式:是指对文件数据进行读取。
RandomAccessFile类有两种构造方法,为
1.RandomAccessFile(fileName,String mode)
2.RandomAccessFile(File,String mode);
第一个参数告诉我们需要访问的文件
第二个参数告诉我们对文件的访问模式
只读模式为"r"代表文件是只读的
方法为RandomAccessFile(file(filename),"r");
1.3读写模式:是指文件进行读取写出
方法为RandomAccessFile(file(fileName),"rw")
表示文件既是可读的,又是可写的。
2.字节数组的读写操作
2.1void write(int d):指对文件进行写出操作
该方法会根据指针的位置吧int类型的值“低八位”写出
代码如下:
/*
* 测试写出方法
*/
public void testWrite() throws IOException{
RandomAccessFile raf=new RandomAccessFile("raf.dat","rw");
//写出一个字节,写的是int值的低8位
raf.write(1);
raf.close();
}
2.2int read():对文件进行读取一个字节操作
该方法会根据指针的位置读取一个int类型值得“低八位”然后输出,高24为为零,取值范围为0-255若读取到了末尾,则返回值为-1
代码如下:
/**
* 测试读取方法
* @throws IOException
*/
public void testRead() throws IOException{
RandomAccessFile raf=new RandomAccessFile("raf.dat","r");
int d=raf.read();
System.out.println(d);
//输出结果:1
raf.close();
}
2.3void write(byte[] d):该方法是指将一组字节写出文件,是连续写出字节中所有字节。
代码如下:
/**
* 测试批量写出
* @throws IOException
*/
public void testWriteByteArray() throws IOException{
RandomAccessFile raf=new RandomAccessFile("raf.dat","rw");
//将字符串按照默认编码格式进行转换为字符数组
byte[]buf="HelloWorld".getBytes();
raf.write(buf);
raf.close();
}
2.4int read(byte[] d):该方法是指将从文件中最大读取数组长度的字节量,返回值为实际得到的字节量。
代码如下:
public void testReadByteArray() throws IOException{
RandomAccessFile raf=new RandomAccessFile("raf.dat","r");
//创建长度为100的字节数组
byte[]buf=new byte[100];
/*
* int write(byte[] b)
* 指从指针开始尝试读取字节数组最大长度,返回值为实际值读取到的字节量
*/
int len=raf.read(buf);
System.out.println(len);
System.out.println(new String(buf));
//读取结果:HelloWorld
raf.close();
}
2.5 void close()是指对文件进行操作后,通过close方法释放系统相关资源。
代码操作:
RandomAccessFile raf=new RandomAccessFile("raf.dat","r");
//文件相关操作
raf.close();
3.文件指针操作
3.1 int getFilePointer()获取当前指针;
RabdomAccessFile的读写操作是基于指针的,就是指总指向当前位置进行读写
当文件被创建后,文件默认的初始地址为0
3.2 void seek(long d);是指对文件指针进行移动操作
3.3 int skipBytes(int n):只用于返回对文件进行跳过n个指针位置,返回值实际跳过的字节数,若返回值为负数,没有跳过任何字节
代码如下:
@Test
public void testPointer() throws IOException{
RandomAccessFile raf=new RandomAccessFile("raf.dat","r");
//输出指针位置,默认从零开始(文件第一个字位置)
System.out.println("指针位置:"+raf.getFilePointer());
//读取world需要将hello这5个字节跳过
int n=raf.skipBytes(5);
System.out.println(n);
//读取world这五个字节
byte[]buf=new byte[5];
raf.read(buf);
System.out.println(new String(buf));
System.out.println("指针位置"+raf.getFilePointer());
//将游标移动到文件开始
raf.seek(0);
System.out.println("指针位置:"+raf.getFilePointer());
raf.close();
}