Author Topic: How to read and write into files in Java?  (Read 984 times)

lachu

  • Newbie
  • *
  • Posts: 7
How to read and write into files in Java?
« on: June 13, 2011, 12:44:42 am »
I want to copy a text file programmatically in Java. What is the easiest way to do it?

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Re: How to read and write into files in Java?
« Reply #1 on: June 14, 2011, 03:57:22 pm »
The following is the sample open which will open the file for reading and compute the amount and write it into another file.

For more details, visit us at: http://www.softwareandfinance.com

import java.io.*;
import java.lang.*;
import java.util.*;

class Sales
{
   public static void main(String args[]) throws Exception
   {
      FileReader fr = new FileReader("sales_input.txt");
      FileWriter fw = new FileWriter("sales_output.txt");
      BufferedReader br = new BufferedReader(fr);

      String s;
      Double totalsales = 0.0;
      Integer totaltickets = 0;

      String out = "Ticket Price\tNo.Tickets\tAmount\n";
      fw.write(out);

      while ((s = br.readLine()) != null)
      {
         String [] tokens = s.split("\t");
         if (tokens.length != 2)
         {
            System.out.println("Error processing record: " + tokens.length);
         }
         else
         {
            Integer unitprice = Integer.parseInt(tokens[0]);
            Integer count = Integer.parseInt(tokens[1]);
            Integer price = count * unitprice;
            totalsales += price;
            totaltickets += count;
            out = unitprice.toString() + "\t\t" + count.toString() + "\t\t" + price.toString() + "\n";
            fw.write(out);
         }
      }
      out = "\t\t" + totaltickets.toString() + "\t\t" + totalsales.toString() + "\n";
      fw.write(out);

      fr.close();
      fw.close();
   }
}

For more details, visit us at: http://www.softwareandfinance.com

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1