RandomAccessFile浅析

时间:2022-03-03 06:00:22

RandomAccessFile类中的write方法有以下的注意事项:

首先write方法每次都写入一个字节

api中write方法如下

public void write(int b) throws IOException {
Object traceContext = IoTrace.fileWriteBegin(path);
int bytesWritten = 0;
try {
write0(b);
bytesWritten = 1;
} finally {
IoTrace.fileWriteEnd(traceContext, bytesWritten);
}
}

可以看出write写入的是一个字节,如果要写入一个int型数据,java api中有writeInt方法,如下:

public final void writeInt(int v) throws IOException {
write((v >>> 24) & 0xFF);
write((v >>> 16) & 0xFF);
write((v >>> 8) & 0xFF);
write((v >>> 0) & 0xFF);
//written += 4;
}

可以看到是api中writeInt方法让然是采用单个字节写入的方法,

v >>> 24) & 0xFF表示将高8位写入。
  
还有一点需要注意的是java官方推荐的做法是在写入读取操作结束后应该使用close方法。
package com.xiaoysec;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays; public class RandomAccessFileTest {
/**
* 测试RandomAccessFile
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("random");
if (!file.exists())
file.mkdir();
File f2 = new File(file, "1.txt");
if (!f2.exists())
f2.createNewFile();
RandomAccessFile raf = new RandomAccessFile(f2, "rw");
raf.write('A');
byte[] buff = new byte[] { 65, 97, 98 };
raf.write(buff);
System.out.println(raf.getFilePointer());
raf.seek(0);
byte[] b = new byte[(int) raf.length()];
raf.read(b);
System.out.println(Arrays.toString(b));
for (byte c : b) {
System.out.print(Integer.toHexString(c) + " ");
}
raf.close();
} }