欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【转】Java 数据流转换工具类

程序员文章站 2022-04-08 17:17:29
...

 

转自:OPEN开发经验库    http://www.open-open.com/lib/view/open1355237678320.html

 

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @ClassName: StreamUtil
 * @Description: 数据流转换工具类
 * @author 
 * @company 
 * @date 2012-12-13
 * @version V1.0
 */

public final class StreamUtil {

	private StreamUtil() {
	}

	/**
	 * @Title: readStreadToByte
	 * @Description: 从输入流中获取数据
	 * @param inStream
	 *            输入流
	 * @return byte[]
	 * @throws Exception
	 * @author 
	 * @date 2012-12-13
	 */
	public static byte[] readStreadToByte(InputStream inStream)
			throws Exception {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buf)) != -1) {

			outStream.write(buf, 0, len);
		}

		byte[] result = outStream.toByteArray();

		outStream.close();
		inStream.close();

		return result;
	}

	/**
	 * @Title: readStreamToString
	 * @Description: 从输入流中获取数据
	 * @param inStream
	 *            输入流
	 * @return String
	 * @throws Exception
	 * @author 
	 * @date 2012-12-13
	 */
	public static String readStreamToString(InputStream inStream)
			throws Exception {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buf)) != -1) {

			outStream.write(buf, 0, len);
		}

		String result = outStream.toString();

		outStream.close();
		inStream.close();

		return result;
	}

	/**
	 * @Title: readStreamToString
	 * @Description: 将输入流转化成某字符编码的String
	 * @param inStream
	 *            输入流
	 * @param encoding
	 *            编码
	 * @return String
	 * @throws Exception
	 * @author 
	 * @date 2012-12-13
	 */
	public static String readStreamToString(InputStream inStream,
			String encoding) throws Exception {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buf)) != -1) {

			outStream.write(buf, 0, len);
		}

		String result = new String(outStream.toByteArray(), encoding);

		outStream.close();
		inStream.close();

		return result;
	}
}
 

 

 

 

 

相关标签: