将文本文件内容保存到链接列表

时间:2016-10-22 18:24:35

标签: java

我正在尝试将word文件的内容逐行保存到LinkedList中。 我究竟做错了什么?控制台显示它是definatley读取文件但不保存其内容?

public class SpellCheck {

LinkedList<String> lines = new LinkedList();

boolean suggestWord ;

public static void main(String[] args) throws java.io.IOException{
    System.out.println("Welcome to the spellchecker");

    LinkedList<String> list = new LinkedList<String>();
    try {
        File f = new File("input/dictionary.txt");
        FileReader r = new FileReader(f);
        BufferedReader reader = new BufferedReader(r);

        String line = null;
        String word = new String(); 
        while((line = reader.readLine()) != null)  
        {      
                list.add(word);
                word = new String();
           }
         reader.close();

    }catch(IOException e) {
        e.printStackTrace();
    }
    for(int i = 0; i<list.size();i++){
        System.out.println(list.get(i));

    }

}   
}

1 个答案:

答案 0 :(得分:1)

您正在添加word这是一个空字符串,而不是添加您从文件中读取的行:

String word = new String(); 
while((line = reader.readLine()) != null)  
{      
     list.add(word);
              ^^^^^
     word = new String();
}

应该是:

while((line = reader.readLine()) != null) {      
      list.add(line);
}