/* Written by Jen Chen Date: updated in Summer 05 */ import java.io.*; import java.util.*; public class File_Writer_tabDelimiter { public static void main(String[] args) throws IOException{ BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); File output = new File("output.txt"); //create a new file for output. output.createNewFile(); //create a new file if necessary. BufferedWriter out = new BufferedWriter(new FileWriter(output)); String fname = "Details.csv"; fname = fname.trim(); BufferedReader in = null; try{ in = new BufferedReader(new FileReader(fname)); } catch(Exception e){ System.out.println("Unable to open the specified file!"); System.out.println(e); System.exit(1); } StringTokenizer st; int qty = 0; double price_unit = 0., sum = 0.; try{ in = new BufferedReader(new FileReader(fname)); String line = in.readLine(); String st3 = "---------------------------------------------------------------------"; String st4 = "Description\t\t\t Unit price\tQuantity\tTotal"; //Print our OWN column HEADER!!! (NOT from the .csv file)"; out.write(st3 + "\n"); //write the column headers to the output file. out.write(st4 + "\n"); //write the column headers to the output file. out.write(st3 + "\n"); //write the column headers to the output file. line = in.readLine(); //read into the next record; ie: we skip the column header. while(line != null){ st = new StringTokenizer(line,","); while(st.hasMoreTokens()){ // linenum > 1 means to skip the header of String st2 = (String) st.nextToken(); //the Details.csv file. (it is String, thus it can't be PARSE!) st2 = st2.trim(); st2 = st.nextToken(); //read into the next token; ie: the 2nd field of the current record. out.write(st2 + "\t"); //write the product's name to the output file. st2 = st.nextToken().trim(); //read into the next token; ie: the 3rd field of the current record. price_unit = Double.parseDouble(st2); out.write("$" + st2 + "\t\t"); //write the per unit price to the output file. st2 = st.nextToken().trim(); //read into the next token; ie: the 4th field of the current record. qty = Integer.parseInt(st2); sum = price_unit*qty; sum = (double) Math.round(sum*100)/100;//round to 2 decimals. out.write(qty + "\t$" + sum + "\n"); //write the quantity & the sum to the output file. st.nextToken(); //Eventhough we don't want to write the last element of the string returns from the StringTokenizer class, //we still HAVE to READ into the REMAINING tokens so that we could get out of this WHILE-loop. //Otherwise we'll get an error message. } //end of the inner WHILE-loop line = in.readLine(); } //end of the OUTER WHILE-loop. } catch(Exception e){ System.out.println(e); System.exit(0); } out.close(); } }