Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Read from a text file named "Input.txt" a list of products.
- * Each product will be in format name + space + price.
- * You should hold the products in objects of class Product.
- * Sort the products by price and write them in format price + space + name
- * in a file named "Output.txt". Ensure you close correctly all used resources. */
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.PrintStream;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Locale;
- import java.util.Scanner;
- public class _09_ListOfProducts {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Locale.setDefault(Locale.ROOT);
- ArrayList<Product> productList = readInputTextFileAndCreateListOfProducts();
- Collections.sort(productList);
- printTheSortedListInOutputTextFile(productList);
- }
- private static ArrayList<Product> readInputTextFileAndCreateListOfProducts() {
- ArrayList<Product> products = new ArrayList<Product>();
- File file = new File("Input.txt");
- try (Scanner scan = new Scanner(file);) {
- while (scan.hasNextLine()) {
- String inputLine = scan.nextLine();
- String[] inputs = inputLine.split("[ ]+");
- Product nextProduct = new Product(inputs[0], inputs[1]);
- products.add(nextProduct);
- }
- } catch (FileNotFoundException e) {
- System.out.println("Error! - The Input text File is Not Found!!!");
- e.printStackTrace();
- }
- return products;
- }
- private static void printTheSortedListInOutputTextFile(
- ArrayList<Product> products) {
- File file = new File("Output.txt");
- try (PrintStream writer = new PrintStream(file);) {
- for (Product product : products) {
- writer.println(product.toString());
- }
- } catch (IOException e) {
- System.out.println("Error! - Has a Problem with Output text File!!!");
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement