/* OutFile.java
 *
 * Ace Kanji Workout
 * Copyright (C) 2006 Alex Quinn <aquinn@cs.washington.edu>
 * Licensed under GPL v2, http://www.gnu.org/licenses/gpl.html
 *
 * Convenience class to simplify file access.  Handles exceptions
 * like runtime exceptions, provides a much simpler constructor,
 * handles non-default encodings gracefully, and provides a few
 * Python-style methods.  A companion InFile is also provided.
 *
 * Author:  Alex Quinn
 * Created: 6/11/2006
 */

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class OutFile {
	static void quickWrite(String s, String enc, String msg) {
		OutFile outfile = new OutFile(s,enc);
		outfile.write(msg);
		outfile.newLine();
		outfile.close();
	}
	protected BufferedWriter bwriter;
	protected boolean alwaysFlush;
	protected boolean append;
	public OutFile(String name, String encoding, boolean alwaysFlush, boolean append) {
		this.alwaysFlush = alwaysFlush;
		this.append = append;
		try {
			bwriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name,append),encoding));
		}
		catch ( IOException e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public OutFile(String name, boolean alwaysFlush) {
		this.alwaysFlush = alwaysFlush;
		try {
			bwriter = new BufferedWriter(new FileWriter(name));
		}
		catch ( IOException e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public OutFile(String name) {
		this(name,false);
	}
	public OutFile(String name, String encoding, boolean alwaysFlush) {
		this(name, encoding,alwaysFlush,false);
	}
	public OutFile(String name, String encoding) {
		this(name,encoding,false,false);
	}



	public void write(String s) {
		write(s,false);
	}
	public void writeLine(String s) {
		write(s,true);
	}
	public void newLine() {
		write(null,true);
	}
	private void write(String s, boolean needNewLine) {
		try {
			if( s != null ) {
				bwriter.write(s);
			}
			if( needNewLine==true ) {
				bwriter.newLine();
			}
			if( alwaysFlush==true ) {
				bwriter.flush();
			}
		}
		catch ( IOException e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public void flush() {
		try {
			bwriter.flush();
		}
		catch ( IOException e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	public void close() {
		try {
			bwriter.flush();
			bwriter.close();
		}
		catch ( IOException e ) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
}
