JAVA高级基础(40)---RandomAccessFile
RandomAccessFile
随机访问文件。可以通过在创建对象的时候,指定模式:r 读模式 / rw 写模式
在其中存在指针,来定位对文件进行读写的位置
- getPointFile(); 获取指针位置
- seek(long pos )设置指针位置
在读取文件的时候,我们要注意一问题:是否存在读取一个字符串的方式。在读的时候,要注意转换为字符串的时候的编码方式
readLine();但是该方法的默认的解码方式时ISO-8859-1
注:具体方法请查找API
package org.lanqiao.randomaccessfile.demo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("aa.txt","r");
//获取指针的位置
System.out.println(raf.getFilePointer());// 0 开始指向文件的开始位置
String strLine = raf.readLine();
System.out.println(raf.getFilePointer());
System.out.println(strLine);
//因为读的时候使用的ISO-8859-1 需要重写进行解码和编码
byte[] b = strLine.getBytes("ISO-8859-1");//使用ISO-8859-1 对读取到的内容进行解码
String str = new String(b,"UTF-8");//再使用UTF-8重新进行编码
System.out.println(str);
//UTF-8 是修改版的UTF-8 会对读取到的内容添加两个字节
System.out.println(raf.getFilePointer());
}
}
package org.lanqiao.randomaccessfile.demo;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo1 {
public static void main(String[] args) throws IOException {
//创建randomaccessfile的读写模式
RandomAccessFile rafOut = new RandomAccessFile("bb.txt","rw");
//读
//RandomAccessFile rafIn = new RandomAccessFile("bb.txt", "r");
//准备写出的数据:
int i = 10;//4
double d = 11.12;//8
boolean b = true;//1
String as = "太";// 3 + 2
String s = "太原师范学院";//18 + 2
//写
rafOut.writeInt(i);
System.out.println("----" + rafOut.getFilePointer());
rafOut.writeDouble(d);
System.out.println("----" + rafOut.getFilePointer());
rafOut.writeBoolean(b);
System.out.println("----" + rafOut.getFilePointer());
rafOut.writeUTF(as);
System.out.println("----" + rafOut.getFilePointer());
rafOut.writeUTF(s);
System.out.println("-----------" + rafOut.getFilePointer());
//将指针移回到文件的开始位置
rafOut.seek(18);
String str = "山西省太原市";
rafOut.writeUTF(str);
rafOut.seek(18);
//读
/*int ii = rafOut.readInt();
System.out.println(ii);
double dd = rafOut.readDouble();
System.out.println(dd);
boolean bb = rafOut.readBoolean();
System.out.println(bb);*/
String ss = rafOut.readUTF();
System.out.println(ss);
//关闭
rafOut.close();
}
}