# General Java Solution & Explanation with Examples

• ``````public int read(char[] buf, int n) {
int curLen = 0;

while(curLen < n){
//create a tmpBuf to store the char get from read4
char[] tmpBuf = new char[4];

//copy from tmpBuf to buf
//copy the min one of len and n-curLen
//example: (from 1-10, read 5, in the second time, you got 4, but actually you just need 5-4=1)
//example: (from 1-10, read 9, in the third time, you got 2, but actually you just need 9-8=1)
//example: (from 1-10, read 12, in the third time, you got 2, len=2, n-curLen(8)=4)
System.arraycopy(tmpBuf, 0, buf, curLen, Math.min(len, n-curLen));

//if len less than 4, means it read to the end, so just return the min of (the stuff I got, the actual stuff I want to return)
//example: (from 1-10, read 9, in the third time, len=2, return(8+2, 9))
//example: (from 1-10, read 12, in the third time, len=2, return(8+2, 12))
if(len < 4) return Math.min(curLen + len, n);
curLen += 4;
}

return n;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.