package org.bench4q.agent.storage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.springframework.stereotype.Component;

@Component
public class LocalStorage implements Storage {

	public String readFile(String path) {
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(
					new FileInputStream(new File(path)), "UTF-8");
			StringBuffer ret = new StringBuffer();
			int toRead;
			while ((toRead = inputStreamReader.read()) != -1) {
				ret.append((char) toRead);
			}
			inputStreamReader.close();
			return ret.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public boolean writeFile(String content, String path) {
		try {
			String dirPath = path.substring(0,
					path.lastIndexOf(System.getProperty("file.separator")));
			File file = new File(dirPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					new FileOutputStream(new File(path), true), "UTF-8");
			outputStreamWriter.write(content);
			outputStreamWriter.flush();
			outputStreamWriter.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
