【问题标题】:import string in ArrayList using buffered reader使用缓冲读取器在 ArrayList 中导入字符串
【发布时间】:2013-11-30 16:34:32
【问题描述】:
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;

public class WordList{

   private static ArrayList<String> words;

  public static void main(String[] args) {
String line;

BufferedReader br = null; 

        try {
          line = null; 
         br = new BufferedReader(new FileReader("filename"));

            while (( line = br.readLine()) != null){
            ArrayList.add(line);// error
            }
        }

            catch (IOException e){
            e.printStackTrace();
        }

finally {
   try {
    if (line == null)br.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
}
}
}

我正在尝试使用 bufferedReader 将 txt 文件中的字符串添加到数组列表中。我不确定如何进行。我试过这条线 ArrayList.add(line); 但它不起作用。错误:无法从静态上下文中引用,非静态方法添加 (E)。 提前谢谢!

【问题讨论】:

    标签: java arraylist static bufferedreader


    【解决方案1】:

    初始化数组列表,如

    words=new ArrayList&lt;String&gt; () ;

    然后拨打words.add(line);

    【讨论】:

      【解决方案2】:

      首先需要初始化ArrayList以避免NPE。

         private static ArrayList<String> words=new ArrayList<>();
      

      使用ArrayList 标识符名称words 添加数据。

          words.add(line);// Use identifier words
      

      【讨论】:

        猜你喜欢
        • 2019-04-10
        • 2015-11-19
        • 1970-01-01
        • 2015-04-10
        • 1970-01-01
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多