Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.text.DecimalFormat;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Formatter;
- import java.util.List;
- import java.util.Scanner;
- public class ReadFile{
- private Scanner scan;
- public void openFile(){
- try{
- scan = new Scanner(new File("Input.txt"));
- }
- catch(FileNotFoundException ex){
- System.err.println("File not found!");
- }
- }
- public void readWriteFile(){
- List<Double> priceList = new ArrayList<Double>();
- List<String> productList = new ArrayList<String>();
- String product = "";
- Formatter formatter = null;
- DecimalFormat df = new DecimalFormat("#.00");
- while(scan.hasNext()){
- product = scan.next();
- double price = Double.parseDouble(scan.next());
- priceList.add(price);
- productList.add(product);
- Collections.sort(priceList);
- // System.out.printf("%s %s\n", priceList, product);
- }
- for (int i = 0; i < priceList.size(); i++) {
- System.out.printf("%s %s\n", df.format(priceList.get(i)), productList.get(i));
- }
- try{
- formatter = new Formatter("Output.txt");
- for (int i = 0; i < priceList.size(); i++) {
- formatter.format("%s %s\r\n", df.format(priceList.get(i)), productList.get(i));
- }
- }
- catch(IOException ioex){
- System.err.println("IO Exception occured.");
- }
- finally{
- formatter.close();
- }
- }
- public void closeFile(){
- scan.close();
- }
- }
- public class TextFileOperations{
- public static void main(String[] args){
- ReadFile rf = new ReadFile();
- rf.openFile();
- rf.readWriteFile();
- rf.closeFile();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement