package com.fuzamei.util;

import java.io.*;

/**
 * 
 * @author wangtao
 * @description IO工具包
 * @createTime 2017-12-6 15:22:02
 *
 */
public class IoUtil {

	private IoUtil(){
		throw new AssertionError("不能实例化 IoUtil");
	}
	/**
	 * 读取输入流为 字节数组
	 * @param inputStream 输入流
	 * @param bufferSize 缓存大小
	 * @return
	 * @throws IOException
	 */
	public static byte[] read(InputStream inputStream, int bufferSize) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[bufferSize];
		for (int num = inputStream.read(buffer); num != -1; num = inputStream.read(buffer)) {
			baos.write(buffer, 0, num);
		}
		baos.flush();
		return baos.toByteArray();
	}
	/**
	 * 读取输入流为字节数组
	 * @param inputStream 输入流
	 * @return
	 * @throws IOException
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		for (int num = inputStream.read(buffer); num != -1; num = inputStream.read(buffer)) {
			baos.write(buffer, 0, num);
		}
		baos.flush();
		return baos.toByteArray();
	}
	/**
	 * 写入文件到指定路径
	 * @param filePath 文件保存路径
	 * @param data 文件数据
	 * @throws IOException
	 */
	public static void write(String filePath, byte[] data) throws IOException {
		FileOutputStream outputStream = new FileOutputStream(filePath);
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
	}
	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 * @param filePath 文件路径
	 * @return 文件内容字符串
	 * @throws IOException
	 */
	public static String readFileByLines(String filePath) throws IOException {
		StringBuilder sbld = new StringBuilder();
        File file = new File(filePath);
		BufferedReader reader = new BufferedReader(new FileReader(file));
    	String tempString = null;
        // 一次读入一行，直到读入null为文件结束
        while ((tempString = reader.readLine()) != null) {
        	sbld.append(tempString);
        }
        reader.close();
        return sbld.toString();
    }

}
