【问题标题】:Java reading words into ArrayList of Strings [duplicate]Java将单词读入字符串的ArrayList [重复]
【发布时间】:2016-03-24 04:20:56
【问题描述】:

我想通过缓冲阅读器将文件 (game-words.txt) 读入字符串的 ArrayList。我已经设置了缓冲阅读器以从 game-words.txt 中读取,现在我只需要弄清楚如何将其存储在 ArrayList 中。提前感谢您的帮助和耐心! 这是我到目前为止所拥有的:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;

class Dictionary{
     String [] words; // or you can use an ArrayList
     int numwords;

    // constructor: read words from a file
    public Dictionary(String filename){ }
    BufferedReader br  = null;
    String line;

    try {

        br = new BufferedReader(new FileReader("game-words.txt"));

    while ((line = br.readLine()) != null){
            System.out.println(line);
    }
    } catch (IOExecption e) {

        e.printStackTrace();
    }

}

【问题讨论】:

  • 您是否在 ArrayList 上查找过 Java API ;) ?
  • Files.readAllLines(Path) 返回List<String>
  • 你能告诉我如何在我的代码中实现它吗?抱歉,Java 新手!
  • 是的,我仍然很困惑:/ @javaPhobic
  • 文件中的单词是如何存储的?他们是每行一个吗?它们是用逗号分隔的吗?

标签: java arraylist


【解决方案1】:

将字符串读入数组:

自动:

List<String> strings = Files.readAllLines(Path);

手册:

List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
            strings.add(line);
    }

将行拆分为单词(如果一行包含多个单词):

for(String s : strings) {
    String[] words = s.split(" "); //if words in line are separated by space
}

【讨论】:

    【解决方案2】:

    这也有帮助:

    class Dictionary{
     ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
     int numwords;String filename;
    
    // constructor: read words from a file
    public Dictionary(String filename){ 
         this.filename =filename;
     }
    BufferedReader br  = null;
    String line;
    
    try {
    
        br = new BufferedReader(new FileReader("game-words.txt"));
    
    while ((line = br.readLine()) != null){
            words.add(line.trim());
    }
    } catch (IOExecption e) {
    
        e.printStackTrace();
    }
    
    }
    

    我使用了 trim ,如果有的话,它将从单词中删除前导和尾随空格。此外,如果您想将文件名作为参数传递,请使用 Filereader 中的文件名变量作为参数。

    【讨论】:

      【解决方案3】:

      是的,您可以使用 arrayList 来存储您要添加的单词。 您可以简单地使用以下内容来反序列化文件。

      ArrayList<String> pList = new ArrayList<String>();
      
      public void deserializeFile(){
          try{
              BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
              String line = null; 
              while ((line = br.readLine()) != null) {
                  // assuming your file has words separated by space
                  String ar[] = line.split(" ");
                  Collections.addAll(pList, ar);
              }
          }
          catch (Exception ex){
              ex.printStackTrace();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-22
        相关资源
        最近更新 更多