此类既可以读也可以写 但是都是针对于文件,不能针对其他节点流
RandomAccessFile不是IO体系的类 父类是Object
public class Demo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
writeAcc();
readAcc();
}
public static void readAcc() throws IOException {
RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "r");
byte[] buf = new byte[1024];
int len = raf.read(buf);
System.out.println(new String(buf,0,len));
}
public static void writeAcc() throws IOException {
RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "rw");
raf.write("这是测试this is test!".getBytes());
raf.close();
}
}
另外可以通过long getFilePointer()函数返回文件记录指针的位置
通过void seek(long pos) 可以将文件记录指针定位到pos的位置
public static void readAcc() throws IOException {
RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "r");
byte[] buf = new byte[1024];
int len = raf.read(buf);
System.out.println(new String(buf,0,len));
System.out.println("当前指针位置:"+raf.getFilePointer());
}
结果:
这是测试this is test!
当前指针位置:21
public static void writeAcc() throws IOException {
RandomAccessFile raf = new RandomAccessFile("C:\\Users\\悠悠华\\Desktop\\test\\ranacc.txt", "rw");
raf.write("这是测试this is test!".getBytes());
raf.seek(40);
raf.write("再来一下:".getBytes());
raf.close();
}
如果再次使用readAcc()读取一次的话结果如下: