**RandomAccessFile是java提供的对文件类容进行访问的类。即可读也可写。
RandomAccessFile可对文件随机访问,可访问文件的任意位置。**
JAVA文件模型
在硬盘上是byte类型存储的,是数据的集合。
(1)打开文件有两种模式
第一种“ rw”(读写),“r”(只读)。
RandomAccessFile fl=new RandomAccessFile(file,”rw”);//这是却定读写的方式
文件指针,打开文件是指针pointer=0;
(2)写方法
fl.write();————–>只写一个字节,指针向后移动一个,指向下一个位置。
(3)读方法
int b=fl.read();————–>只读一个字节
读之前必须把指针移到头部。
package filetext;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class WrTest {
public static void main(String[] args)throws IOException {
File file=new File("deom");//生成文件
if(!file.exists()) {
file.mkdirs();
}
File file2=new File(file,"rat.src");//生成文件子目录
if(!file2.exists()) {
file2.createNewFile();
}
RandomAccessFile flAccessFile=new RandomAccessFile(file2,"rw");
//写文件
flAccessFile.write('A');//一次只写入一个字节
int i=0x7fffffff;//相当于4个字节
flAccessFile.writeInt(i);
System.out.println(flAccessFile.getFilePointer());//此时指针指向5
String string="中";
byte[] gbk=string.getBytes("gbk");//直接将“中”转为字节数组
flAccessFile.write(gbk);
System.out.println(flAccessFile.length());
//读文件,必须把指针移到头部
flAccessFile.seek(0);
//一次读取文件中所有的内容
byte[] buf=new byte[(int)flAccessFile.length()];//文件本身就是字节
flAccessFile.read(buf);
System.out.println(Arrays.toString(buf));
for (byte b : buf) {
System.out.println(Integer.toHexString(b&0xff)+" ");//以16进制方式输出
}
flAccessFile.close();//读完之后要将其关闭
}
}
本文通过实例介绍了 Java 中 RandomAccessFile 类的使用方法,包括如何打开文件、读写操作及定位文件指针等关键技术点。
3万+

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



