package com.jiayue.ipfcst.client.protocol2file;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * 生成文件的工具类
 *
 * @author: xiuwei
 * @version:
 */
public class GenerateFileUtil {


	/**
	 * 读取字串的编码格式
	 */
	private static final String DEFAULT_ENCODING = "GBK";

	/**
	 * 最长读取字节
	 */
	private static final int PROTECTED_LENGTH = 51200;

	private GenerateFileUtil() {
	}

	public static final GenerateFileUtil getInstance() {
		return LazyHolder.INSTANCE;
	}

	/**
	 * 为了单例的内部类
	 *
	 * @return 实例
	 */
	private static class LazyHolder {
		private static final GenerateFileUtil INSTANCE = new GenerateFileUtil();
	}


	private String demoFileContent;


	/**
	 * 读取输入流里面的字符串
	 *
	 * @param input
	 * @return
	 * @throws Exception
	 */
	public String readInfoStream(InputStream input) throws Exception {
		if (input == null) {
			throw new Exception("输入流为null");
		}
		//字节数组
		byte[] bcache = new byte[2048];
		//每次读取的字节长度
		int readSize = 0;
		//总字节长度
		int totalSize = 0;
		ByteArrayOutputStream infoStream = new ByteArrayOutputStream();
		try {
			//一次性读取2048字节
			while ((readSize = input.read(bcache)) > 0) {
				totalSize += readSize;
				if (totalSize > PROTECTED_LENGTH) {
					throw new Exception("输入流超出50K大小限制");
				}
				//将bcache中读取的input数据写入infoStream
				infoStream.write(bcache, 0, readSize);
			}
		} catch (IOException e1) {
			throw new Exception("输入流读取异常");
		} finally {
			try {
				//输入流关闭
				input.close();
			} catch (IOException e) {
				throw new Exception("输入流关闭异常");
			}
		}

		try {
			return infoStream.toString(DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			throw new Exception("输出异常");
		}
	}


	/**
	 * 获取模版文件的内容
	 *
	 * @return
	 * @throws Exception
	 */
	public String getDemoFileContent() throws Exception {
		if (demoFileContent == null) {
			InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("example.xml");
			demoFileContent = readInfoStream(inputStream);
		}
		return demoFileContent;
	}


}
