如果在Java中想在写入的文件中进行定位操作,可以使用随机访问类RandomAccessFile进行定位写覆盖,使用其提供的seek方法,根据写入的数据类型计算大小进行定位。
写入文件的方式是byte类型。所以进行了int与byte类型的转换,由于数据类型小,所以只转换了16位(int 32位,short16位)。
public class FileTest {
private String fileString = "test.dat";
public void test()
{
try {
File file = new File(fileString);
FileOutputStream fileOutputStream = new FileOutputStream(file);
RandomAccessFile fileAccessFile = new RandomAccessFile(file,"rw");
int[] testString = {1,2,3};
int [] outInt = new int[3];
byte[] outByte = new byte[6];
byte[] outByte2 = new byte[12];
int[] outInt2 = new int[6];
outByte = int2byte(testString, 3);
for(int i:testString)
System.out.println("testString="+String.valueOf(i));
fileOutputStream.write(outByte);
fileAccessFile.seek(2);//在第3个位置进行插入覆盖
fileAccessFile.write(outByte);
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(outByte2);
outInt2 = byte2int(outByte2, 6);
fileOutputStream.close();
fileAccessFile.close();
fileInputStream.close();
for(int i:outInt2)
System.out.println("outInt2="+String.valueOf(i));
} catch (Exception e) {
// TODO: handle exception
}
}
private byte[] int2byte(int[] array,int len)
{
byte[] out = new byte[len*2];
for(int i=0;i<len;i++)
{
out[2*i] = (byte)(array[i]&0xff);
out[2*i + 1] = (byte)(array[i]>>8);
}
return out;
}
private int[] byte2int(byte[] array,int len)
{
int[] out = new int[len];
for(int i=0;i<len;i++)
{
out[i] = (int)((array[2*i+1]<<8) | (array[2*i]&0xff));
}
return out;
}
}
输出结果,可以看出第二个数字往后被覆盖,fileOutputstream只能进行顺序写入,不会记录随机访问的位置,如果再进行fileoutputstream写入,则是其之前结束的位置再写入。
testString=1
testString=2
testString=3
outInt2=1
outInt2=1
outInt2=2
outInt2=3
outInt2=0
outInt2=0