package de.ugoe.cs.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * <p>
 * Helper class that provides methods that simplify working with files.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class FileTools {

	/**
	 * <p>
	 * Private constructor to prevent initializing of the class.
	 * </p>
	 */
	private FileTools() {

	}

	/**
	 * <p>
	 * Returns an array of the lines contained in a file. The line separator is
	 * "\r\n".
	 * </p>
	 * 
	 * @param filename
	 *            name of the file
	 * @return string array, where each line contains a file
	 * @throws IOException
	 *             see {@link FileReader#read(char[])},
	 *             {@link FileReader#close()}
	 * @throws FileNotFoundException
	 *             see {@link FileReader#FileReader(File)}
	 */
	public static String[] getLinesFromFile(String filename)
			throws IOException, FileNotFoundException {
		return getLinesFromFile(filename, true);
	}

	/**
	 * <p>
	 * Returns an array of the lines contained in a file.
	 * </p>
	 * 
	 * @param filename
	 *            name of the file
	 * @param carriageReturn
	 *            if true, "\r\n", if false "\n" is used as line separator
	 * @return string array, where each line contains a file
	 * @throws IOException
	 *             see {@link FileReader#read(char[])},
	 *             {@link FileReader#close()}
	 * @throws FileNotFoundException
	 *             see {@link FileReader#FileReader(File)}
	 */
	public static String[] getLinesFromFile(String filename,
			boolean carriageReturn) throws IOException, FileNotFoundException {
		File f = new File(filename);
		FileInputStream fis = new FileInputStream(f);
		InputStreamReader reader = new InputStreamReader(fis,
				Charset.defaultCharset());
		char[] buffer = new char[(int) f.length()];
		reader.read(buffer);
		reader.close();
		String splitString;
		if (carriageReturn) {
			splitString = "\r\n";
		} else {
			splitString = "\n";
		}
		return (new String(buffer)).split(splitString);
	}

}
