/**
* Authour: Deleepa
* Date: 07/06/2013
* Project: Hangman | RemoveWordService
*/
package service;
import java.util.ArrayList;
import java.util.Collections;
import utils.ReadFile;
import utils.WriteToFile;
public class RemoveWordService {
public RemoveWordService() {
}
/*
* In this method, first all the words from the text file are retrieved
* and fed into an arraylist. Then the program will check if a word similar
* to the one fed into the method exists. If so, the word will be removed
* from the array list. The words that are not removed are fed into a
* normal string array.
* This array is then sent to the WriteToFile class, where the dictionary
* file is truncated and rewritten.
*/
public boolean removeWord(String word) {
ReadFile reader = new ReadFile();
WriteToFile writer = new WriteToFile();
ArrayList<String> allWords = new ArrayList<String>();
boolean wordRemoved = false;
String path = "dictionary.txt";
allWords = reader.readFromFile(path);
allWords.removeAll(Collections.singleton(null));
System.out.println("old size: " + allWords.size());
for(int i = 0; i < (allWords.size() - 1); i++) {
if(word.equals(allWords.get(i))) {
allWords.remove(i);
wordRemoved = true;
}
}
allWords.removeAll(Collections.singleton(null));
String[] toBeWritten = new String[allWords.size()];
for (int j = 0; j < allWords.size(); j++) {
System.out.println(allWords.get(j));
toBeWritten[j] = allWords.get(j);
}
System.out.println("tobewritten: " + toBeWritten.length);
System.out.println("New size: " + allWords.size());
for (int k = 0; k < toBeWritten.length; k++) {
System.out.println("toBeWritten: " + toBeWritten[k]);
}
try {
writer.truncateAndWriteFile("dictionary.txt", toBeWritten);
} catch(Exception e) {
System.out.println("Error: " + e);
}
if(wordRemoved) {
return true;
}else {
return false;
}
}
}