Its pretty late to answer this question, but still someone else will find it useful in future.
Check this(viewtopic.php?f=43&t=94) thread, Code samples are in JAVA.
But you can get good understanding how to buffer and read input stream...
one thing i would like to add is,.. you can buffer your output as well for better time. Check tutorial problem Enormous Input and Output.