【问题标题】:Putting every word in a file into an array list [closed]将文件中的每个单词放入数组列表中[关闭]
【发布时间】:2015-11-28 00:22:47
【问题描述】:

缓冲阅读器的新手,我正在尝试将文件放入数组列表中......这就是我目前所拥有的。

  FileReader in = new FileReader(latestFile);
    BufferedReader br = new BufferedReader(in);

    int arrayCount = 0;
    String[] array = null;

    String nextLine = null;
    if ((nextLine = br.readLine()) != null ) {
        arrayCount = array.length;
        array[arrayCount - 1] = nextLine.split("\\s+");

    }

谁能解释我做错了什么?

【问题讨论】:

  • 你能更准确地描述你的问题吗?
  • 除了使用答案中提到的List<String> 之外,您还可以使用从BufferedReader 构造的Scanner 来读取单词,而不是读取一行并将其拆分

标签: java arraylist bufferedreader


【解决方案1】:

只需将String[] array = null; 更改为List<String> arrayList = new ArrayList<>(); 并将array[arrayCount - 1] = nextLine.split("\\s+"); 更改为arrayList.add(nextLine.split("\\s+"));

即使用ArrayList 而不是未定义的数组。

【讨论】:

  • 刚刚尝试了添加数组列表的第二部分。它在添加部分不断产生错误。我也添加了All,但是没有用。
  • 什么错误???提供stacktrace这么难?
【解决方案2】:
BufferedReader file = new BufferedReader(new FileReader("yourfile.txt"));

ArrayList<String> array = new ArrayList<String>();

String line;
while ((line = file.readLine()) != null) 
{
    array.add(line.split("\\s+"));
}
file.close();

基本上,您逐行读取文件并将每一行添加到字符串数组列表中。

如果你想访问元素,你可以这样做:

for (int i=0; i < array.size(); i++)
   System.out.println(array.get(i)); 

【讨论】:

  • 如果我错了,请纠正我,但这并没有将它们分开。从我的打印输出来看,它似乎是根据行将它们分开的。
  • 你说得对,我编辑了答案。谢谢。
【解决方案3】:
  • 问题是您尚未初始化Array 对象,为此,您必须知道要从文件中读取的元素数量。 所以你可以将数组初始化为

    String[] array = new String[The Number];
    
  • 由于您不太可能知道数组中的元素数量,因此您必须使用ArrayList

    FileReader in = new FileReader(latestFile);
    BufferedReader br = new BufferedReader(in);
    
    // This list will dynamically grow as elements are inserted.
    ArrayList<String> arraylist = new ArrayList<String>();
    
    String nextLine = null;
    if ((nextLine = br.readLine()) != null ) {
      arraylist.addAll(Arrays.asList(line.split("\\s+")));
    }
    
    // if you want an array, following code will return all the 
    //elements as String array
    String[] array = arraylist.toArray(new String[0]);
    

    使用ArrayList 会很容易。

    希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 2016-06-28
    • 2016-08-11
    • 2013-05-19
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多