RandomAccessFile支持对于文件的随机访问(而不是只能从头开始读写),创建RandomAccessFile对象时需要传入mode参数,该参数有4个值:r(read), rw(read,write), rws(read, write and store data and file into device memory),rwd((read, write and store file into device memory).
public class RandomAcessFileTest {
public static void main(String[] args) {
try (RandomAccessFile raf = new RandomAccessFile("newFile.txt", "rw")) {
System.out.println("The initial local of RandomAccessFile's index:"
+ raf.getFilePointer());
byte[] bbuf = new byte[1024];
int hasRead = 0;
while ((hasRead = raf.read(bbuf)) > 0) {
System.out.println(new String(bbuf, 0, hasRead));
}
// move the index
raf.seek(20);
raf.write("hello, apend\r\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
京公网安备 11010502036488号