/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.cqcis.com</a>
 */
package com.crunii.micro.common.utils;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author 田平 create 2014-8-21下午3:11:20
 */
public class FileUtil {

	/**
	 * 自动补全文件路径以反斜杠结尾
	 *
	 * @param path
	 * @return
	 */
	public static String getRealPath(String path) {
		if (StringUtils.hasText(path) && !path.endsWith("/")) {
			return path + "/";
		} else {
			return path;
		}
	}

	public static FileInputStream getFileInputStream(String path) {
		try {
			return new FileInputStream(new File(path));
		} catch (IOException e) {
			throw new RuntimeException("getInputStream error!", e);
		}
	}

	public static FileOutputStream getFileOutputStream(String path) {
		try {
			return new FileOutputStream(new File(path));
		} catch (IOException e) {
			throw new RuntimeException("getOutputStream error!", e);
		}
	}

	public byte[] getFileBytes(String path) {
		try {
			return FileUtils.readFileToByteArray(new File(path));
		} catch (IOException e) {
			throw new RuntimeException("file read error!", e);
		}
	}

	public static String getFileContent(String pathname) {
		return getFileContent(pathname, Charsets.UTF_8);
	}

	public static void writeFile(String path, String text) {
		writeFile(path, text, Charsets.UTF_8);
	}

	public static void writeFile(String path, String text, Charset charset) {
		File file = new File(path);
		try {
			Files.asCharSink(file, charset).write(text);
		} catch (Exception e) {
			throw new RuntimeException("file write error!", e);
		}
	}

	public static String getFileContent(String pathname, Charset charset) {
		String result = null;
		File file = new File(pathname);
		try {
			result = Files.asCharSource(file, charset).read();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("File read error!", e);
		}
		return result;
	}

	public static void deleteFileOrDir(File path) {
		if (!path.exists())
			return;
		if (path.isFile()) {
			path.delete();
			return;
		}
		File[] files = path.listFiles();
		for (int i = 0; i < files.length; i++) {
			deleteFileOrDir(files[i]);
		}
		path.delete();
	}

	public static void main(String[] args) {
		String xml = getFileContent("C:\\Users\\Administrator\\Desktop\\data.txt");
		System.out.println(xml);
	}

}
