RandomAccessFile可以实现文件数据的随机读取,即:通过对文件内部读取位置的自由定义,以实现部分数据的读取操作,所以在使用此类操作时就必须保证写入数据时数据格式与长度统一


范例:使用RandomAccessFile写入数据
package com.lxh.sixteenchapter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class JavaIODemo421 {
public static void main(String[] args) {
File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
if(!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
RandomAccessFile raf=new RandomAccessFile(file,"rw");
//要保存的姓名数据,为保证长度一致,使用空格填充
String name[]=new String[]{"zhangsan","lisi ","wangwu "};
int age[]=new int [] {17,23,40};
//循环写入
for(int x=0;x<name.length;x++) {
raf.write(name[x].getBytes());
raf.writeInt(age[x]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
范例:使用RandomAccessFile读取数据
package com.lxh.sixteenchapter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class JavaIODemo422 {
public static void main(String[] args) {
File file=new File("E:"+File.separator+"File"+File.separator+"ll.txt");
RandomAccessFile raf=null;
try {
raf=new RandomAccessFile(file,"rw");
{
//读取王五的数据,跳过24位
raf.skipBytes(24);
byte data[]=new byte[8];
int len=raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
}
{
//读取李四的数据,回跳12位
raf.seek(12);
byte data[]=new byte[8];
int len=raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
}
{
//读取张三的数据,回跳到开始点
raf.seek(0);
byte data[]=new byte[8];
int len=raf.read(data);
System.out.println("姓名:"+new String(data,0,len).trim()+"年龄:"+raf.readInt());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(raf!=null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
执行结果
姓名:wangwu年龄:40
姓名:lisi年龄:23
姓名:zhangsan年龄:17
本文详细介绍并演示了Java中RandomAccessFile类的使用方法,包括如何通过该类实现文件数据的随机读写,以及在读写过程中如何保证数据格式与长度的一致性。文章通过具体示例代码展示了数据的写入与读取过程。
204

被折叠的 条评论
为什么被折叠?



