/**
 * BufferStuff.java
 * Reads lines of text from the keyboard and saves it to a file named
 * by a command line argument.
 *
 * Illustrates buffer problems. Both the input and the output are buffered.
 * This is for efficiency reasons but can cause programming problems.
 * Note the comments below and the use of  skip(), available() and the "true"
 * argument in the PrintWriter constructor.
 *
 * DG Nov. 99
 */

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;

public class BufferStuff {

	public static void main(String [] args) {

		BufferedReader br = null;
		PrintWriter pw = null;
		File f = null;
		String line = null;

		if(args.length != 1) {
			System.out.println("USAGE: java BufferStuff <filename>");
			System.exit(0);
		}

		f = new File(args[0]);
		if(f.exists()) {
			System.out.println("File Exists. Overwrite? (y/n)");
			try {
				switch(System.in.read()) {
					// There is a buffer here too. Try removing the skip()
					// Then, if the user types 'y' an empty string is still
					// there (!) which will cause  an immediate exit of the
					// while loop below. On the other hand, if the user types
					// "yes" (still without the skip(), the 'y' will be consumed
					// and the "es" written to the file!
					case 'y': System.in.skip(System.in.available());
							  break;
					default: System.exit(0);
				}
			}
			catch (IOException e) {}
		}

		try {
			// "true" here flushes the output buffer after every pw.println().
			// You could instead call pw.flush() after each pw.println().
			// (Actually, this is not needed in this particular program.)
			pw = new PrintWriter(new FileWriter(f), true);
			br = new BufferedReader(new InputStreamReader(System.in));

			do {
				System.out.println("Enter a line. To stop, press <enter>");
				line = br.readLine();
				pw.println(line);
			}
			while(!line.equals(""));
			br.close();
			pw.close();
		}
		catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
}