【发布时间】:2018-09-02 06:31:52
【问题描述】:
我只需要读取一个文本文件一次并将句子存储到一个 ArrayList 中。然后,我需要将句子的 ArrayList 拆分为每个单词的另一个 ArrayList。不知道该怎么做?
在我的代码中,我已将所有单词拆分为一个 ArrayList,但我认为它再次从文件中读取,这是我做不到的。
到目前为止我的代码:
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();
}
}
}
【问题讨论】:
-
您只阅读了一次文件。为什么你认为你会不止一次地阅读它?
-
你到底是什么意思?
readLine()不代表你阅读了整个文件。 -
感谢链接,暗淡。这些说明看起来就像你循环浏览文件一样,它会再次读取它。我不确定每个 for 循环是否都在重新读取文件。