The API: int read4(char *buf)
reads 4 characters at a time from a file.
The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
By using the read4
API, implement the function int
read(char *buf, int n)
that reads n characters from the file.
Note:
The read
function will only be called once for each test case.
/* The read4 API is defined in the parent class Reader4.
int read4(char[] buf); */
public class Solution extends Reader4 {
/**
* @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) {
for(int i = 0; i < n; i += 4){
char[] buffer = new char[4];
int length = read4(buffer);//read4 每次读4个char
System.arraycopy(buffer, 0, buf, i, length);
if(length < 4){
return Math.min(i + length, n);//读到最后file里面char不足的时候 不是返回n
}
}
return n;
}
}