package com.mingsoft.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.apache.log4j.Logger;


/**
 * io流读取文件
 * 
 * @author Administrator 荣繁奎
 */
public class IoReader {
	private static Logger LOG = Logger.getLogger(IoReader.class);
	/**
	 * 去读全部的内容 可以一一行的方式读取出来
	 * 
	 * @param url需要读取的文件地址
	 * @return String
	 */
	public static String readForAll(String path) {
		String pathRe = path;
		File file = new File(pathRe);
		BufferedReader reader = null;
		StringBuffer bufer = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;

			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				bufer.append(tempString + "\n");
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return bufer.toString();
	}


	/**
	 * i/o进行读取htm模版
	 * 
	 * @return fileContent读出的内容
	 */
	public static String readFile(String url) {
		String path = url;
		String fileContent = "";
		try {
			File f = new File(path);
			if (f.isFile() && f.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(f), "UTF-8");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent += line + "\n";
				}
				read.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileContent;
	}

	/**
	 * i/o写入文件
	 * 
	 * @param content
	 *            写入文件内容
	 * @param writePath
	 *            要写入的文件名路径
	 */
	public static void writeFile(String content, String writePath,
			String charCoder) {
		try {
			File file = new File(writePath);
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), charCoder);
			BufferedWriter reader = new BufferedWriter(osw);
			reader.write(content);
			reader.close();
			osw.close();

		} catch (Exception e) {
			LOG.error("读取文件内容操作出错");
			e.printStackTrace();
		}
	}

}
