Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class CsvFileWriter {
- //delimiter
- private static final String COMMA_DELIMITER = ",";
- private static final String NEW_LINE_SEPARATOR = "\n";
- //header
- private static final String FILE_HEADER = "amount, unit, ingredient, tags";
- public static void writeCsvFile(String recipeName) {
- ArrayList<Ingredients> ingredientList = createIngredientList();
- FileWriter fileWriter = null;
- try {
- fileWriter = new FileWriter(recipeName + ".csv");
- fileWriter.append(FILE_HEADER.toString());
- fileWriter.append(NEW_LINE_SEPARATOR);
- for(Ingredients i : ingredientList) {
- fileWriter.append(String.valueOf(i.getAmount()));
- fileWriter.append(COMMA_DELIMITER);
- fileWriter.append(i.getUnit());
- fileWriter.append(COMMA_DELIMITER);
- fileWriter.append(i.getTags());
- fileWriter.append(COMMA_DELIMITER);
- fileWriter.append(i.getIngredient());
- fileWriter.append(NEW_LINE_SEPARATOR);
- }
- System.out.print("Recipe " + recipeName + " was created!");
- } catch (Exception e) {
- System.out.print("Error in CSV-FileWriter!!");
- e.printStackTrace();
- }finally {
- try {
- fileWriter.flush();
- fileWriter.close();
- } catch (IOException e) {
- System.out.println("Error while flushing/closing fileWriter !!!");
- e.printStackTrace();
- }
- }
- }
- public static ArrayList<Ingredients> createIngredientList() {
- Scanner scan = new Scanner(System.in);
- ArrayList<Ingredients> list = new ArrayList<Ingredients>();
- char quit = 'Y';
- String unit, ingredient, tags;
- double amount;
- while(quit == 'Y') {
- System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
- System.out.print("Amount: ");
- amount = scan.nextDouble();
- System.out.print("Unit: ");
- unit = scan.next();
- System.out.print("Ingredient: ");
- ingredient = scan.nextLine();
- System.out.print("Tags (e.g. tag;tag;tag): ");
- tags = scan.nextLine();
- list.add(new Ingredients(amount, unit, ingredient, tags));
- System.out.print("More Ingredients? (Y/N) ");
- String s = scan.next();
- s = s.toUpperCase();
- quit = s.charAt(0);
- }
- return list;
- }
- public static void main (String[] args) {
- System.out.print("Type recipe name here: ");
- Scanner scan = new Scanner(System.in);
- String recipeName = scan.next();
- writeCsvFile(recipeName);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement