import java.io.*;

/**
 * Demonstrate use of DataInput/OutputStreams with merchandise invoices.
 * 
 * @author CSCI209
 */
public class DataIODemo {

	/**
	 * 
	 * @param args
	 *            - not used in this program
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {

		// I know I don't want this variable to change within this method, so
		// made it final
		final String FILENAME = "invoice.dat";

		// stream to write the data out; file will contain bytes because it's an OutputStream
		DataOutputStream out = new DataOutputStream(new FileOutputStream(
				FILENAME));

		double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
		int[] units = { 12, 8, 13, 29, 50 };
		String[] descs = { "Java T-shirt", "Java Mug", "Java Beach Towel",
				"Java Pin", "Java Key Chain" };

		// write the data out
		for (int i = 0; i < prices.length; i++) {
			out.writeDouble(prices[i]);
			out.writeChar('\t');
			out.writeInt(units[i]);
			out.writeChar('\t');
			out.writeChars(descs[i]);
			out.writeChar('\n');
		}
		out.close();

		// read the data in again
		DataInputStream in = new DataInputStream(new FileInputStream(FILENAME));

		double price;
		int unit;
		StringBuilder desc;
		double total = 0.0;

		final String lineSepString = System.getProperty("line.separator");
		char lineSep = lineSepString.charAt(0);

		while (in.available() > 0) {
			price = in.readDouble();
			in.readChar(); // throws out the tab
			unit = in.readInt();
			in.readChar(); // throws out the tab
			char chr;
			desc = new StringBuilder(20);
			while ((chr = in.readChar()) != lineSep)
				desc.append(chr);
			System.out.println("You've ordered " + unit + " units of " + desc
					+ " at $" + price);

			total = total + unit * price;
		}
		in.close();

		// 2 ways to do the same thing:
		System.out.printf("For a TOTAL of $%.2f\n", total);
		// OR
		System.out.format("For a TOTAL of $%.2f", total);
	}
}
