老师留作业,要扫描一个文件并且将文件中的单词逐个添加进一个List<String>里去。那个文件每个单词占一行,我想用 .add(split("\n")[i])这个方法在一个循环里实现,但是我发现在\n处分割只能把第一个元素添加进List里,之后的全部没有。我用打印了一下split("\n").length,发现长度只有一。是因为read的扫描器只能扫描一行吗?
后面是代码,求教,谢谢!
public class WordFisher
{
public HashMap<String, Integer> vocabulary;
private List<String> stopwords;// (to be instantiated as an ArrayList)
private String inputTextFile;
private String stopwordsFile;
public WordFisher(String inputTextFile, String stopwordsFile) throws IOException
{
this.inputTextFile = inputTextFile;
this.stopwordsFile = stopwordsFile;
stopwords = new LinkedList<String>();
getStopwords();
}
private void getStopwords() throws IOException
{
try
{
BufferedReader input = new BufferedReader(new FileReader(stopwordsFile));
String read = input.readLine();
int i = 0;
String[] string = read.split("n");
while(i < string.length)
{
stopwords.add(string[i]);
i++;
}
input.close();
for(int k = 0; k < stopwords.size(); k++)
{
System.out.println(stopwords.get(k));
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}