Advertisement
coasterka

TextFileOperations

May 16th, 2014
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.text.DecimalFormat;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.Formatter;
  8. import java.util.List;
  9. import java.util.Scanner;
  10.  
  11. public class ReadFile{
  12.    
  13.     private Scanner scan;
  14.    
  15.     public void openFile(){
  16.         try{
  17.             scan = new Scanner(new File("Input.txt"));
  18.         }
  19.         catch(FileNotFoundException ex){
  20.             System.err.println("File not found!");
  21.         }
  22.     }
  23.    
  24.     public void readWriteFile(){
  25.         List<Double> priceList = new ArrayList<Double>();
  26.         List<String> productList = new ArrayList<String>();
  27.         String product = "";
  28.         Formatter formatter = null;
  29.         DecimalFormat df = new DecimalFormat("#.00");
  30.         while(scan.hasNext()){
  31.             product = scan.next();
  32.             double price = Double.parseDouble(scan.next());
  33.             priceList.add(price);
  34.             productList.add(product);
  35.             Collections.sort(priceList);
  36. //          System.out.printf("%s %s\n", priceList, product);
  37.         }
  38.         for (int i = 0; i < priceList.size(); i++) {
  39.             System.out.printf("%s %s\n", df.format(priceList.get(i)), productList.get(i));
  40.         }
  41.         try{
  42.             formatter = new Formatter("Output.txt");
  43.             for (int i = 0; i < priceList.size(); i++) {
  44.                 formatter.format("%s %s\r\n", df.format(priceList.get(i)), productList.get(i));
  45.             }
  46.         }
  47.         catch(IOException ioex){
  48.             System.err.println("IO Exception occured.");
  49.         }
  50.         finally{
  51.             formatter.close();
  52.         }
  53.     }
  54.    
  55.     public void closeFile(){
  56.         scan.close();
  57.     }
  58. }
  59.  
  60.  
  61. public class TextFileOperations{
  62.    
  63.     public static void main(String[] args){
  64.         ReadFile rf = new ReadFile();
  65.         rf.openFile();
  66.         rf.readWriteFile();
  67.         rf.closeFile();
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement