RandomAccessFile的使用类似于C语言的文件读写,可以实现随机的对文件进行读写插入添加
其中mode的可选参数为:
读写文件
//进行文件的读、写
@Test
public void test1(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("hello.txt"), "r");
raf2 = new RandomAccessFile(new File("hello1.txt"),"rw");
byte[] b = new byte[20];
int len;
while((len = raf1.read(b)) != -1){
raf2.write(b, 0, len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
插入:
public void test4(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello1.txt"),"rw");
raf.seek(4);
byte[] b = new byte[10];
int len;
StringBuffer sb = new StringBuffer();
while((len = raf.read(b)) != -1){
sb.append(new String(b,0,len));
}
raf.seek(4);
raf.write("xy".getBytes());
raf.write(sb.toString().getBytes());
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(raf != null){
try {
raf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}