Given read4k, implement readanysize

The key here is to maintain a buffer of 4k by your self, and read from this buffer.

import java.util.ArrayList;
import java.util.List;

public class AnysizeRead {
	private final int SIZE = 4096;
	//assume you are given a method that reads 4k data, implement readanysize method using this method.
	int curr = 0;
	List<Integer> buff = new ArrayList<Integer>();
	public List<Integer> readAnySize(int size) {
		List<Integer> result = new ArrayList<Integer>();
		while(size > 0) { //keep reading until finished reading all the size
			if (curr + size < SIZE) {
				result.addAll(buff.subList(curr, curr + size));
				curr += size;
				size = 0;
			}
			else {
				result.addAll(buff.subList(curr, buff.size()));
				curr = 0;
				size -= SIZE - curr;
				buff = read4k();
			}
		}
		return result;
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s