------- android培训、java培训、期待与您交流! ----------
RandomAccessFile
随机访问文件,自身具备读写的方法.
通过skipBytes(int x),seek(int x)来达到随机访问
与普通的输入输出流不一样的是RamdomAccessFile可以任意的访问文件的任何地方
该类不算IO体系中的子类,而是直接继承自Object
但是它是IO包中的成员,因为它具备读写功能,内部封装了一个数组,
而且通过指针对数组中的元素进行操作,可以通过getFilePointer获取指针位置
用于标识当前流的读写位置,同时可以通过seek改变指针的位置,这个位置可以向前移动,也可以向后移动
其实完成读写的原理就是因为它内部封装了字节输入和输出流
通过它的构造函数可以看出,该类只能操作文件
而且操作文件还有模式
RandomAccessFile的构造方法如下
mode的值有四个,其中两个比较常用
"r":以只读文方式打开指定文件.。如果你写的话会有IOException.
"rw":以读写方式打开指定文件,不存在就创建新文件.
该对象包含两个方法来操作文件记录指针.
long getFilePoint():记录文件指针的当前位置.
void seek(long pos):将文件记录指针定位到pos位置.
RandomAccessFile包含InputStream的三个read方法,
也包含OutputStream的三个write方法.
同时RandomAccessFile还包含一系列的readXxx和writeXxx方法完成输入输出.
public class RandomAccessFileDemo
{
public static void main(String[] args)
{
}
public static void writeFile()throws IOException
{
RandomAccessFile raf = new RandomAccessFile("ran,txt","rw");
raf.write("李武".getBytes());
raf.write(97);
raf.close();
}
//从文件中间读取
public static void midRead() throws Exception
{
RandomAccessFile raf=new RandomAccessFile("work","r");
raf.seek(4);
byte []buffer=new byte[100];
int len=0;
while((len=raf.read(buffer, 0, 100))!=-1)
{
System.out.println(new String(buffer,0,len));
}
}
public static void endWrite_2() throws Exception
{
RandomAccessFile raf=new RandomAccessFile("work","rw");
raf.seek(raf.length());
raf.write("hello world!".getBytes());
raf.close();
}
}