package client.util;

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

public class FileUtils {
	public static final Charset UTF_8 = Charset.forName("UTF-8");
	
	public static String read(File file) throws IOException {
		FileInputStream in = null;
		String s;
		try {
			in = new FileInputStream(file);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buffer = new byte[4096];
			long count = 0L;
			int n;
			for(boolean u = false; -1 != (n = in.read(buffer)); count += (long)n) {
				output.write(buffer, 0, n);
			}
			s = new String(output.toByteArray(), UTF_8);
		}
		finally {
			try {
				if(in != null)
					in.close();
			}
			catch(IOException e) {
			}
		}
		return s;
	}

	public static void write(File file, String data) throws IOException {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			if(out != null) {
				out.write(data.getBytes(UTF_8));
				out.close();
			}
		}
		finally {
			try {
				if(out != null)
					out.close();
			}
			catch(IOException e) {
			}
		}
	}
	
	public static InputStream getResource(String path) throws FileNotFoundException {
		InputStream in = FileUtils.class.getResourceAsStream("/" + path);
		if(in == null)
			throw new FileNotFoundException(path);
		return in;
	}
}
