Java使用RandomAccessFile读写文本文件

来源:互联网 发布:会声会影x2软件下载 编辑:程序博客网 时间:2024/05/18 00:09

指定位置写入

RandomAccessFile file = new RandomAccessFile("c:\\k.txt", "rw");
 file.seek(2*2);//跳过俩个字节

file.write("人".getBytes());//防止乱码


指定位置读取

 RandomAccessFile raf = new RandomAccessFile("c:\\k.txt", "r"); 
 raf.seek(2);//设置指针的位置为文件的开始部分  
 byte[] bytes = new byte[12];  
 for (int i=0; i<bytes.length; i++)  
 bytes[i] = raf.readByte();//每次读一个字节,并把它赋值给字节bytes[i]  
 String stringValue = new String(bytes);           
 System.out.println(stringValue);