IO流复制

IO流只能操作一次,如果需要多次读取流获取其中的信息,就需要将流进行复制,再对每个流进行单独操作(流只能使用一次!

/**
* 复制操作流
 */
public void uploadFile(MultipartFile file,HttpSession session){

	InputStream is = file.getInputStream();
	ByteArrayOutputStream same = cloneInputStream(is);
	
	//stream1  stream2 两个流可进行独自流的操作
	InputStream stream1 = new ByteArrayInputStream(same.toByteArray()); 
    InputStream stream2 = new ByteArrayInputStream(same.toByteArray()); 
}


/**
* InputStream 改为ByteArrayOutputStream 
 */
 private static ByteArrayOutputStream cloneInputStream(InputStream input) {
	try {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
        int len;
		while ((len = input.read(buffer)) > -1) {
			baos.write(buffer, 0, len);
		}
		baos.flush();
		return baos;
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/chinasi2012/article/details/86017362