Post

IO

Read N Characters Given Read4 II - Call multiple times

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution extends Reader4 {
    private char[] buff = new char[4];
    private int p = 0;
    private int count = 0;  // count of bytes in buff from file
    
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    public int read(char[] buf, int n) {
        int index = 0;
        while (index < n) {
            // all 4 bytes in buff are read
            if (p == count) {
                count = read4(buff);
                // resets point to the beginning of buffer
                p = 0;
                
                // 0 byte is read from file
                if (count == 0) {
                    break;
                }
            }
            
            while (index < n && p < count) {
                buf[index++] = buff[p++];
            }
        }
        return index;
    }
}
This post is licensed under CC BY 4.0 by the author.