创建文件访问对象:
File file=new File("cost.dat");
if (!file.exists()){
file.createNewFile();
}
文件读取:
//rw表示可以进行读写操作
//r表示读取文件信息
RandomAccessFile raf=new RandomAccessFile(file,"rw");
获取文件指针节点函数:
raf.getFilePointer();
文件信息写入函数:
raf.write(9);
获取文件字节数;
file.length();
让文件指针偏移到指定位置:
raf.seek(0);//偏移到0位置
跳过字节函数:
raf.skipBytes(3);//跳过三位置,指针往后偏移三
一个一个字节读取文件信息:
raf.read();
注意:文件的写入和读取按照:0000 0000 0000 0000写入和读取,只能吸入低八位,也就是后面八位,超过八位的内容将不会被写入也不会被读取。
按照字节数组写入文件:
String name=sc.nextLine();
//1.首先得到name的字节byte数组
byte[] bytes=name.getBytes();
System.out.println(bytes.length);
//2.按照输入数据的byte数组直接写入文件
raf.write(bytes);
按照字节数组读取文件:
//5.读取文件信息,按照数组
byte[] readBytes=new byte[1024];
int index=raf.read(readBytes);
System.out.println("读取到了:"+index+"个字节");
//6.将读取到的byte数组信息转换为字符串信息
String s=new String(readBytes);
System.out.println("读取到的文件内容:"+s);
判断文件是否读取完毕:
//read()==-1[0,255] 表示读取完毕
while(raf.read()!=-1) {}