2011-03-15 60 views
3

我想覆盖文件的最后26个字节。基本上我需要在那里放一些整数和字节变量。我试图与FileOutputStream一起使用DataOutputStream,但这些东西没有seek()方法或类似的东西。那么我怎么能做一个writeInt()从(文件大小 - 26)开始?我看到有一个写入方法接受偏移量,但我不确定它是否是我想要的,如果是这样,如何将int,long和字节变量转换为byte []以传递到该方法。Java - 覆盖二进制文件的一部分

谢谢您的建议

回答

3

使用RandomAccessFile你可以沿着这些路线做一些事情:

File myFile = new File (filename); 
//Create the accessor with read-write access. 
RandomAccessFile accessor = new RandomAccessFile (myFile, "rws"); 
int lastNumBytes = 26; 
long startingPosition = accessor.length() - lastNumBytes; 

accessor.seek(startingPosition); 
accessor.writeInt(x); 
accessor.writeShort(y); 
accessor.writeByte(z); 
accessor.close(); 

我希望它能帮助!让我知道它是否足够好。

+0

他可以直接使用'accessor.writeInt(int)'类方法,而不需要将每个字节数组打包到一个字节数组中。 – 2011-03-15 21:47:01

+0

谢谢你的好例子,RandomAccessFile就是我正在寻找的东西。 – Marius 2011-03-15 22:26:56