public int read(char[] buf, int n) {
// file has less than n chars
// n is not divisible by 4
boolean EOF = false;
char[] temp = new char[4];
int curPtr = 0;
while(curPtr < n && !EOF){
int charCount = read4(temp);
EOF = (charCount < 4);
for(int i = 0; i < charCount && curPtr < n; i++){
buf[curPtr++] = temp[i];
}
}
return curPtr;
}
public class Solution extends Reader4 {
char[] leftOver = new char[4];
int leftCount = 0;
int leftPtr = 0;
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
public int read(char[] buf, int n) {
int totalLen = 0; // always points to next pos to be filled
boolean EOF = false;
char[] temp = new char[4];
while(!EOF && totalLen < n){
while(leftCount > 0 && totalLen < n){
buf[totalLen++] = leftOver[leftPtr++];
leftCount--;
}
if(totalLen < n){
int newLen = read4(temp);
EOF = newLen < 4;
if(totalLen + newLen <= n){
// did not exceed
for(int i = 0; i < newLen; i++) buf[totalLen++] = temp[i];
} else {
// points to next extra char
int ptr = 0;
// write needed char into buffer
while(totalLen < n) buf[totalLen++] = temp[ptr++];
// write extra char into leftover
int size = newLen - ptr;
for(int i = 0; i < size; i++){
leftOver[i] = temp[ptr++];
leftCount = i + 1;
}
leftPtr = 0;
}
}
}
return totalLen;
}
}