這是OutputStream的一個(gè)子類,其輸出設(shè)備是內(nèi)存,準(zhǔn)確來(lái)說(shuō)是RAMFile,即將數(shù)據(jù)寫(xiě)入到RAMFile的Vector中去。
該類有一個(gè)最重要的方法,現(xiàn)在把它整個(gè)貼出來(lái)
public void flushBuffer(byte[] src, int len) {
int bufferNumber = pointer/BUFFER_SIZE; //buffer序列,即當(dāng)前所寫(xiě)B(tài)uffer在RAMFile中的Vector中的序列號(hào)
int bufferOffset = pointer%BUFFER_SIZE; //偏移量,即當(dāng)前所寫(xiě)字節(jié)在當(dāng)前Buffer中的偏移量。
int bytesInBuffer = BUFFER_SIZE - bufferOffset; //當(dāng)前Buffer的剩余可寫(xiě)字節(jié)數(shù)
//bytesToCopy是實(shí)際寫(xiě)入的字節(jié)數(shù),如果當(dāng)前Bufer的剩余字節(jié)數(shù)大于需要寫(xiě)的字節(jié)的總數(shù)則寫(xiě)入所有字節(jié)
//否則,將當(dāng)前Buffer寫(xiě)滿即可,剩余的字節(jié)將寫(xiě)入下一個(gè)Buffer
int bytesToCopy = bytesInBuffer >= len ? len : bytesInBuffer;
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[BUFFER_SIZE]); //在RAMFile中添加新的byte[1024]元素
byte[] buffer = (byte[])file.buffers.elementAt(bufferNumber);
System.arraycopy(src, 0, buffer, bufferOffset, bytesToCopy);
if (bytesToCopy < len) { // not all in one buffer,
int srcOffset = bytesToCopy;
bytesToCopy = len - bytesToCopy; // remaining bytes 剩余的未寫(xiě)入的字節(jié)數(shù)
bufferNumber++; //將buffer數(shù)增加1
if (bufferNumber == file.buffers.size())
file.buffers.addElement(new byte[BUFFER_SIZE]);
buffer = (byte[])file.buffers.elementAt(bufferNumber); //剩余字節(jié)寫(xiě)入下一個(gè)Buffer
System.arraycopy(src, srcOffset, buffer, 0, bytesToCopy);
}
pointer += len;
if (pointer > file.length)
file.length = pointer; //移位文件指針 在原有的基礎(chǔ)上加上實(shí)際寫(xiě)入的字節(jié)總數(shù)
file.lastModified = System.currentTimeMillis(); //修改文件的最后修改時(shí)間為當(dāng)前時(shí)間
}
從指定的字節(jié)數(shù)組復(fù)制指定長(zhǎng)度的字節(jié)到RAMFile中去。由于RAMFile中Vector的元素是byte[1024]所以可能存在做一次該操作
要操作兩個(gè)Vector元素的情況。即先將當(dāng)前byte[1024]數(shù)組填滿,再新建一個(gè)元素裝載剩余的字節(jié)。
另外還有一個(gè)writeTo(OutputStream out)方法,將RAMFile中的數(shù)據(jù)輸出到另一個(gè)輸出流