commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From manoj mokashi <manojmoka...@gmail.com>
Subject [IO] Copy Streams with length and bufferSize
Date Tue, 06 Mar 2012 07:12:03 GMT
Hi,

would like to suggest a copy method for streams that takes a length
and buffer size as arguments.
Something like the below. Maybe we could also have a start offset and
use the skip method to reach it.

-----------------------

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtil {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream( "c:/temp/tarlog.txt");
			fos = new FileOutputStream( "c:/temp/tarlog_copy.txt");
			copyStream( fis, fos, 100, 100);
		}
		finally {
			fis.close();
			fos.close();
		}
	}

	// copy the specified len bytes of inputstream to the outputstream,
	// using the bufferSize.
	public static void copyStream( InputStream is, OutputStream os, int
len, int bufferSize) throws IOException {
		int totalread = 0;
		byte[] barr = new byte[ bufferSize];
		while( (len == -1 || totalread < len ) ){
			int read = is.read( barr, 0, len ==-1 ? bufferSize :
Math.min(len-totalread, bufferSize) );
			if( read == -1){
				break;
			}
			else {
				os.write( barr, 0, read);
				totalread += read;
			}
		}
	}

}

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org


Mime
View raw message