I need to read a text file only once and store the sentences into an ArrayList. Then, I need to split the ArrayList of sentences into another ArrayList of each individual word. Not sure how to go about doing this?
In my code, I've split all the words into an ArrayList, but I think it's reading from the file again, which I can't do.
My code so far:
public class Main {
public static void main(String[] args){
try{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
ArrayList<String> sentences = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
String line;
while((line=br.readLine()) != null){
String[] lines = line.toLowerCase().split("\\n|[.?!]\\s*");
for (String split_sentences : lines){
sentences.add(split_sentences);
}
/*Not sure if the code below reads the file again. If it
does, then it is useless.*/
String[] each_word = line.toLowerCase().split("\\n|[.?!]\\s*|\\s");
for(String split_words : each_word){
words.add(split_words);
}
}
fr.close();
br.close();
String[] sentenceArray = sentences.toArray(new String[sentences.size()]);
String[] wordArray = words.toArray(new String[words.size()]);
}
catch(IOException e) {
e.printStackTrace();
}
}
}