RandomAccessFile的write(byte[] d,int offset,int len)方法
RandomAccessFile还有许多写入方法,如writeInt(),writeLong()...writeXXX()方法,这次主要讲出场率高的write(byte[] d,int offset,int len)方法。
示例代码如下:
/*
* write(byte[] d,int offset,int len)
* 该方法会根据当前指针所在位置处连续写出改定数组中的部分字节,
* 这个部分是从数组的offset处开始,连续读len个字节
*/
@Test
public void testWriteByByteArray() throws IOException{
RandomAccessFile raf = new RandomAccessFile("test.txt","rw");
RandomAccessFile raf2 = new RandomAccessFile("test_copy.txt","rw");
byte[] b = new byte[1024*10];
int len = -1;
while((len=raf.read(b))!=-1){
raf2.write(b,0,len);
}
}
分析:该方法通俗讲,写入字节数组所装的数据,但是就上面的例子而言,如果读取的数据达到10K了,自然全部写入,如果读的数据不足10K,就4K,那么就要确定一下写入的数据长度了,于是write(byte[] b)有了一个重载方法write(byte[] b,int offset ,int len)