Tuesday, 22 December 2015

Lazyness

Fed up of writing to a text file everyday what I do in the day ready for tomorrow's scrum, from what I have read I can make a bat file put into windows start up folder and no more typing the same thing everyday.

It does need a couple of changes, keen to keep one file per year which then this program would create as needed once updated. It does seem a bit much on the try catch however I do not want to create new entries if I need to reboot during the work day.

Also seems strange to me that to add to the start of the file I need to write it all again.

package com.company;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * Created by R on 22/12/2015.
 */
public class diaryWriter {
    private String path = "";
    private LocalDate today = LocalDate.now();
    private DateTimeFormatter formatter =   

      DateTimeFormatter.ofPattern("dd-MM-yyy");
    private String message;

    public void writeMessageToDiary() {
        message = today.format(formatter)
                + "\nTested"
                + "\nTest Cases"
                + "\nRaised"
                + "\nComplete"
                + "\nNotes"
                + "\n\n";

        //Only write to file if not been written to today
        if ( !isTodayLatest() ) {
            prependMessageToFile();
        }
    }

    private boolean isTodayLatest() {
        String firstLine = "";

        try (BufferedReader bufferedReader = 

         new BufferedReader(new FileReader(path))) {
            firstLine = bufferedReader.readLine();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return firstLine.equals(today.format(formatter));
    }

    private void prependMessageToFile() {
        //Read file to a string
        StringBuilder fileString = new StringBuilder();
        String line;
        try (BufferedReader bufferedReader = 

           new BufferedReader(new FileReader(path))) {
            while ( (line = bufferedReader.readLine()) != null) {
                fileString.append(line + "\n");
            }
        } catch (IOException e) {
            e.getStackTrace();
        }

        //Write complete file back to path
        try (BufferedWriter bufferedWriter = 

          new BufferedWriter(new FileWriter(path))){
            bufferedWriter

            .append(fileString.insert(0, message).toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment