Demo entry 2569696

TextBuddy

   

Submitted by Varun on Aug 30, 2015 at 16:47
Language: Java. Code size: 8.0 kB.

//package com.company;

import java.io.*;
import java.util.Scanner;

public class TextBuddy {

    private static final String MESSAGE_WELCOME = "Welcome to TextBuddy. %1$s is ready for use";
    private static final String MESSAGE_INVALID_ARGUMENTS = "Invalid number of arguments specified. Try again.";
    private static final String MESSAGE_INVALID_FORMAT = "invalid command format :%1$s";
    private static final String MESSAGE_ADDED = "added to %1$s: \"%2$s\"";
    private static final String MESSAGE_DELETED = "deleted from %1$s: \"%2$s\"";
    private static final String MESSAGE_CLEARED = "all content deleted from %1$s";
    private static final String MESSAGE_UNABLE_TO_SAVE = "Unable to save file";
    private static final String MESSAGE_UNABLE_TO_ADD_LINE = "Unable to write line.";
    private static final String MESSAGE_UNABLE_TO_OPEN_FILE = "Unable to open file";
    private static final String MESSAGE_UNABLE_TO_CLEAR = "Unable to clear file";
    private static final String MESSAGE_UNABLE_TO_DELETE_LINE = "Unable to delete line";

    // These are the possible command types
    enum COMMAND_TYPE {
        ADD_LINE, DELETE_LINE, DISPLAY, CLEAR, INVALID, EXIT
    };

    private static Scanner scanner = new Scanner(System.in);
    private static String fileName;
    private static FileWriter fileWriter;


    public static void main(String[] args) {
	    if (args.length == 1) {
            fileName = args[0];
            boolean fileOpenSuccess = openFile(fileName);
            if (!fileOpenSuccess) {
                showToUser(MESSAGE_UNABLE_TO_OPEN_FILE);
            }
            showToUser(String.format(MESSAGE_WELCOME, fileName));
            while (true) {
                System.out.print("command: ");
                String command = scanner.nextLine();
                String feedback = executeCommand(command);
                showToUser(feedback);
            }
        } else {
            showToUser(MESSAGE_INVALID_ARGUMENTS);
        }
    }

    public static String executeCommand(String userCommand) {
        if (userCommand.trim().equals("")) {
            return String.format(MESSAGE_INVALID_FORMAT, userCommand);
        }

        String commandTypeString = getFirstWord(userCommand);

        COMMAND_TYPE commandType = determineCommandType(commandTypeString);

        switch (commandType) {
            case ADD_LINE:
                return addLine(userCommand);
            case DELETE_LINE:
                return deleteLine(userCommand);
            case DISPLAY:
                return display(userCommand);
            case CLEAR:
                return clear();
            case INVALID:
                return String.format(MESSAGE_INVALID_FORMAT, userCommand);
            case EXIT:
                saveFile();
                System.exit(0);
            default:
                //throw an error if the command is not recognized
                throw new Error("Unrecognized command type");
        }
    }

    private static String clear() {

        try {
            fileWriter = new FileWriter(fileName);
            return String.format(MESSAGE_CLEARED, fileName);
        } catch (IOException e) {
            return String.format(MESSAGE_UNABLE_TO_CLEAR);
        }


    }

    private static String display(String userCommand) {
        File inputFile = new File(fileName);
        String currentLine;

        try {
            int count = 1;
            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader =
                    new BufferedReader(new FileReader(inputFile));
            while((currentLine = bufferedReader.readLine()) != null) {
                showToUser(count + ". " + currentLine);
                count++;
            }

            // To check if file is empty (count will not be incremented)
            if (count == 1) {
                return fileName + " is empty";
            }
            // Always close files.
            bufferedReader.close();
            return null;
        }
        catch(FileNotFoundException ex) {
            return MESSAGE_UNABLE_TO_OPEN_FILE;
        }
        catch(IOException ex) {
            return MESSAGE_UNABLE_TO_OPEN_FILE;
        }
    }

    private static String deleteLine(String userCommand) {

        int lineNumToDelete = Integer.parseInt(removeFirstWord(userCommand));
        String currentLine;
        String lineToDelete = "";
        boolean lineDeleted = false;
        int lineCount = 1;
        try {
            File inputFile = new File(fileName);
            File tempFile = new File("myTempFile.txt");

            BufferedReader reader = new BufferedReader(new FileReader(inputFile));
            BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

            while((currentLine = reader.readLine()) != null) {

                // trim newline when comparing with lineToRemove
                String trimmedLine = currentLine.trim();
                if(lineCount++ == lineNumToDelete) {
                    lineToDelete = currentLine;
                    lineDeleted = true;
                    continue;
                }
                writer.write(currentLine + System.getProperty("line.separator"));
            }

            writer.close();
            reader.close();
            tempFile.renameTo(inputFile);

            if (!lineDeleted) {
                return MESSAGE_UNABLE_TO_DELETE_LINE;
            } else {
                return String.format(MESSAGE_DELETED, fileName, lineToDelete);
            }
        } catch (IOException e) {
            return MESSAGE_UNABLE_TO_DELETE_LINE;
        } finally {
            openFile(fileName);
        }
    }

    private static String addLine(String userCommand) {

        String lineToAdd = removeFirstWord(userCommand);
        try {
            fileWriter.write(lineToAdd);
            fileWriter.write('\n');
            fileWriter.flush();
            return String.format(MESSAGE_ADDED, fileName, lineToAdd);
        } catch (IOException e) {
            showToUser(MESSAGE_UNABLE_TO_ADD_LINE);
            return "";
        }
    }

    private static COMMAND_TYPE determineCommandType(String commandTypeString) {
        if (commandTypeString == null) {
            throw new Error("command type string cannot be null!");
        }
        if (commandTypeString.equalsIgnoreCase("add")) {
            return COMMAND_TYPE.ADD_LINE;
        } else if (commandTypeString.equalsIgnoreCase("delete")) {
            return COMMAND_TYPE.DELETE_LINE;
        } else if (commandTypeString.equalsIgnoreCase("display")) {
            return COMMAND_TYPE.DISPLAY;
        } else if (commandTypeString.equalsIgnoreCase("clear")) {
            return COMMAND_TYPE.CLEAR;
        } else if (commandTypeString.equalsIgnoreCase("exit")) {
            return COMMAND_TYPE.EXIT;
        } else {
            return COMMAND_TYPE.INVALID;
        }
    }

    private static void saveFile() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            showToUser(MESSAGE_UNABLE_TO_SAVE);
        }


    }
    private static String removeFirstWord(String userCommand) {
        return userCommand.replace(getFirstWord(userCommand), "").trim();
    }

    private static String getFirstWord(String userCommand) {
        String commandTypeString = userCommand.trim().split("\\s+")[0];
        return commandTypeString;
    }

    private static void showToUser(String text) {
        if (text != null) {
            System.out.println(text);
        }
    }

    private static boolean openFile(String name) {
        try {
            fileWriter = new FileWriter(name, true);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).