package com.leanwo.activiti.service.base.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.inject.Named;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.service.base.FileService;

@Named
public class FileServiceImpl implements FileService{

	private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
	
	@Override
	public void createFile(String filePath, byte[] bytes){
		OutputStream outputStream = null;
		InputStream inputStream = null;
		File file = new File(filePath);
		File fileParent = file.getParentFile();
		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}
		try {
			outputStream = new FileOutputStream(filePath);
			inputStream = new ByteArrayInputStream(bytes);
			byte[] buff = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buff)) != -1) {
				outputStream.write(buff, 0, len);
			}
		} catch (FileNotFoundException e1) {
			logger.error("BPMN文件生成失败。", e1);
		} catch (IOException e) {
			logger.error("BPMN文件生成失败。", e);
		}finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					logger.error("BPMN文件生成失败。", e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					logger.error("BPMN文件生成失败。", e);
				}
			}
		}
	}
}
