【问题标题】:return arraylist from a file从文件中返回数组列表
【发布时间】:2016-10-18 23:11:23
【问题描述】:

方法获取文件名,我需要返回一个ArrayList<<ArrayList<String>>,其中每一行都转换为ArrayList<String>,每个字符串都是该行中的一个单词。

我的txt文件是这个

Twinkle twinkle little star
How I wonder what you are
Up above the world so high
Like a diamond in the sky

所以它应该返回一个大小为 4 的数组列表,其元素是大小为 4 的字符串的数组列表,第二个元素是大小为 6 的字符串的数组列表,依此类推

但是我不确定如何将行变成单个字符串,这就是我目前所拥有的

public static ArrayList<ArrayList<String>> file (String fname){
  ArrayList<ArrayList<String>> w1 = new ArrayList<ArrayList<String>>();
  ArrayList<String> w2 = new ArrayList<String>();
  try{ 
    BufferedReader br = new BufferedReader (new FileReader(fname));
    String line= "";    

    while ((line = br.readLine()) != null){
        w2.add(line);
        w1.add(w2);
    }

  }catch(IOException e){
      System.out.println("An error occured");
  } 
  return w1;
}

【问题讨论】:

  • 对于您阅读的每一行,您需要 1) 将其拆分为单词 2) 将这些单词添加到 new ArrayList&lt;String&gt;,然后 3) 添加 ArrayList&lt;String&gt;到更大的ArrayList&lt;ArrayList&lt;String&gt;&gt;

标签: java file arraylist


【解决方案1】:
public static ArrayList<ArrayList<String>> file (String fname){
      ArrayList<ArrayList<String>> w1 = new ArrayList<ArrayList<String>>();
      ArrayList<String> w2 = new ArrayList<String>();
      try{ 
        BufferedReader br = new BufferedReader (new FileReader(fname));
        String line= "";    

        while ((line = br.readLine()) != null){
            //take each line and split them around a space
            String[] individualWords = line.split("\\s+");
            //now convert the string[] to an arraylist
            w2 = new ArrayList<>(Arrays.asList(individualWords));
            //now add it to your main arraylist of arraylist strings
            w1.add(w2);
        }

      }catch(IOException e){
          System.out.println("An error occured");
      } 
      return w1;
    }

【讨论】:

  • line.split( "\\s+" ); 可能会更好,因为它会在任何空格字符上分割行。
  • 这听起来是个好主意,我会做出改变,谢谢
【解决方案2】:

也许只是

public static ArrayList<ArrayList<String>> file (String fname){
    return Files.lines(Paths.get(fname))
                .map(line -> line.split("\\s+"))
                .map(words -> Arrays.stream(words).collect(Collectors.toList()))
                .collect(Collectors.toList());
}

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多