一、RandomAccessFile类
RandomAccessFile是java输入\输出流体系中功能最为丰富的文件内容访问类
RandomAccessFile对象提供了一个记录指针,有两种方法操作:long getFilePoint()返回当前指针位置、void seek(long pos)将文件的指针定位到pos的位置。
创建RandomAccessFile对象时需要传入两个参数,第一个可用String、File对象来指定,第二个参数包含四种形态:
“r”:只读方式
“rw”:读取、写入方式
“rws”同上,文件的内容和元数据的每个更新同步写入底层存储设备
“rwd”同“rw”,文件的内容的每个更新同步写入底层存储设备
以下程序对文件进行操作:
package java_test;
import java.io.*;
public class RandomAccessFileTEST {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
RandomAccessFile rf=null;
try
{
//以只读方式打开文件
rf=new RandomAccessFile("d:\\abc.txt","r");
//显示初始指针的位置
System.out.println("初始指针的位置"+rf.getFilePointer());
//跳转指针
rf.seek(2);
//
byte[] b=new byte[1024];
int index=0;
while((index=rf.read(b))>0)
{
System.out.println(new String(b,0,index));
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
rf.close();
}
}
}
下面程序实现了向文件指定位置插入内容的功能
package java_test;
import java.io.*;
public class InsertContent
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
InsertContent.insert("d:\\abc.txt",0,"chian");
}
public static void insert(String filename,long pos,String insertcontent) throws IOException
{
RandomAccessFile rf=null;
//创建一个临时文件来保存插入点后的数据
File tmp=File.createTempFile("temp", null);
FileInputStream fis=null;
FileOutputStream fos=null;
tmp.deleteOnExit();
try
{
rf=new RandomAccessFile("d:\\abc.txt","rw");
fis=new FileInputStream(tmp);
fos=new FileOutputStream(tmp);
rf.seek(pos);
//先把指针后的数据存入tmp中
byte[] b=new byte[32];
int index=0;
while((index=rf.read(b))>0)
{
fos.write(b,0,index);
}
//重新定位指针,把自己想要的数据写入文件中
rf.seek(pos);
//把内容加入
rf.write(insertcontent.getBytes());
//把temp中的内容加入
while((index=fis.read(b))>0)
{
rf.write(b,0,index);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
rf.close();
}
}
}
二、序列化
序列化允许将实现了序列化的对象转换为字节序列,从而存储在磁盘上或者通过网络传输,并还原对象。
如果需要实现序列化,必须实现两个接口之一:Serializable、Externalizable