/* Written by Jen Chen Updated on June, 2005. Copyrighted by Jen Chen An example to manipulate the fields in a csv file then redirect the result to a tab delimited file. */ import java.io.*; import java.util.*; public class File_Writer { public static void main(String[] args) throws IOException{ 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 total = 1, qty = 0; double price_unit = 0., sum = 0.; try{ in = new BufferedReader(new FileReader(fname)); String line = in.readLine(); //read into the column headers. String st3 = "---------------------------------------------------------------------"; System.out.println(st3); System.out.printf("%-35s%-15s%-10s%-20s","Description","Unit price","Quantity","Total"); System.out.println(st3); out.write(st3 + "\n"); //write the column headers to the output file. out.write("Description\tUnit Price\t\tQuantity\tTotal" + "\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 first record. while(line != null){ st = new StringTokenizer(line, ","); //Tokenize the string.. String st2 = (String) st.nextToken(); //the Details.csv file. (it is String, thus it can't be PARSE!) st2 = st.nextToken(); //read the next token.(the 2nd field) st2 = st2.trim(); //remove all blank spaces; if there is any. System.out.printf("%-35s$",st2); //print the product's name. (2nd field) out.write(st2 + "\t"); //write the product's name to the output file. st2 = st.nextToken(); //read to the next token (the 3rd field). price_unit = Double.parseDouble(st2); System.out.printf("%5s",price_unit); //Assign 5 spaces to this string; then print the string right-aligned. st2 = st.nextToken(); //read into the next token. (the 4th field) qty = Integer.parseInt(st2); System.out.printf("%12s",qty); //Assign 12 spaces to this string; then print the string right-aligned. out.write("$" + st2 + "\t\t"); //write the per unit price to the output file. sum = price_unit*qty; System.out.printf("%15.2f\n",sum); //Assign 15 spaces to this double value; then print the string right-aligned. out.write(qty + "\t$" + sum + "\n"); //write the quantity & the sum to the output file. line = in.readLine(); //read into the next record. } } catch(Exception e){ System.out.println(e); System.exit(0); } out.close(); //close the output file so that its contents will be written to the output file. } //end of main() } //end of class File_IO5{}