您的位置:首页 > 其它

随机访问类(RandomAccessFile)

2010-12-14 22:33 330 查看
随机访问类(RandomAccessFile)
随机访问类(RandomAccessFile) - []
输入流FileInputStream和输出流 FileOutputStream,实现的是对磁盘文件的顺序读写,而且读写要分别创建不同对象。相比之下RandomAccessFile类则可对文件实现随机读写操作。
RandomAccessFile对象的文件位置指针遵循下面的规律:
·新建RandomAccessFile对象的文件位置指针位于文件的开头处;
·每次读写操作之后,文件位置的指针都相应后移到读写的字节数;
·可以通过getFilePointer方法来获得文件位置指针的位置,通过seek方法来设置文件指针的位置。
如果某个文件有30个字节,读取数据过程中,从20-30读取,用skip( )//跳过方法,但在读取的过程中,前面的字节都被删除掉了,如果用户有这样的需求,先读取10-20字节,之后再读1-10之间的数,再20-30之间,
java.io
随机访问文件类 RandomAccessFile java.io.RandomAccessFile
所有已实现的接口:
Closeable, DataInput, DataOutput

|0 ||10 ||20 ||30 |
(指示器)
RandomAccessFile常用方法:
skipBytes(long i):从前往后拨弄指示器的位置,就是跳过多少个字节读取数据。
Void seek(long p): 对指示器作决定性的定位,用于从后往前拨弄指示器的位置。对于seek方法,拥有skipBytes( )的功能,但seek( )在使用过程非常影响系统的开销。只有万不得已的情况下使用。

例:seek(0) 指示器移到首部

RandomAccessFile类,即可以充当输入也可充当输出流。可以看作节点流。
构造方法:
RandomAccessFile (”路径+文件名”, String“rw”/”r”)两个参数,
//创建模式:“rw”代表写流,“r”代表读流,
RandomAccessFile常用方法
Void close( )
Long length( )
Void seek( )
##Long getFilePointer( )获得当前指针位置,默认为0 ,
Int read( )从文件当前位置读取一个字节
int read (byte[]b)
int read (byte[]b,int off,int len)
Final boolean readBoolean( )从文件当前位置读取boolean类型的一个字节 boolean在内存占1/8
Final char readChar( )从文件中读取2个字节。
Final int readInt( )从文件中读取4个字节。
##Final String readLine( )从文件中读取一行后转为String。
Void write(byte[]b)将字节数组B中的数据写到文件中。
Void write(byte[]b,int off,int len)将 len 个字节从指定字节数组写入到此文件,并从偏移量 off 处开始。

Void write(int b)将指定的数据写到文件中。
Final void writeBoolean(boolean v)将boolean类型的值按单字节的形式写到文件中0或1
Final void writeChar(int v)将char值按2个字节写入到文件中
Final void writeChars(String s)将字符串按字符方式写入到文件中
Final void writeInt(int v)按四个字节将 int 写入该文件,先写高字节

Java代码
例:getFilePointer( )
import java.io.*;

class df
{
public static void main(String args[])throws Exception
{
RandomAccessFile s=new RandomAccessFile("d:/tt.txt","rw");
System.out.println ( s.getFilePointer( ));//0
}
}

例:getFilePointer( )
import java.io.*;

class df
{
public static void main(String args[])throws Exception
{
RandomAccessFile s=new RandomAccessFile("d:/tt.txt","rw");
System.out.println ( s.getFilePointer( ));//0
}
}

例: Java代码
import java.io.*;
class RandomAccessFileDemo
{

public static void main(String args[])throws IOException

{

RandomAccessFile f=new RandomAccessFile("myfile","rw");
System.out.println ("File.lelngth:"+(f.length( ))+"B");
System.out.println ("File PointPosition:"+f.getFilePointer( ));
f.seek(f.length( ));
f.writeBoolean(true);
f.writeBoolean(false);
f.writeChar(’a’);
f.writeChars("hello!");
System.out.println ("File Length;"+(f.length( ))+"B");

f.seek(0);
System.out.println (f.readBoolean( ));
System.out.println (f.readBoolean( ));
//while(f.getFilePointer( )
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: