【问题标题】:Split comma-separated file per line into Array将每行逗号分隔的文件拆分为数组
【发布时间】:2015-07-01 08:43:56
【问题描述】:

目标:我正在尝试将 .txt 文件处理为 String[]。文件必须按行读取,拼接在“,”上并存储在数组中。每个元素(每行 6 个元素)必须在数组中有自己的索引,并且必须可以单独访问。

文件(部分):

210,20140101,    1,   60,   67,   -1
210,20140101,    2,   60,   65,    0
210,20140101,    3,   60,   58,    0
210,20140101,    4,   60,   56,    0
210,20140101,    5,   60,   49,    0
210,20140101,    6,   60,   53,    0
210,20140101,    7,   60,   55,    0
210,20140101,    8,   70,   59,    0

到目前为止的代码:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    for (String line; (line = br.readLine()) != null;) {
        counter++;
        if (counter > 51) {
            line = br.readLine();
            line = line.trim();
            list = Arrays.asList(line.split("\\s*,\\s*"));
        }
    }
}

for (String x : list) {
    System.out.println(x);
}

目前的输出:

391
20141231
24
20
1
0

这正是我需要的,但对于每一行(存储在字符串数组中)。使用上面的代码,只有文件的最后一行存储在数组中。

我已经尝试了herehere 的建议。 有什么建议或提示吗?

【问题讨论】:

  • 我可以知道你为什么使用 counter>51 吗?
  • 不需要文件的前 51 行。 if 语句让我处理该行之后的数据。 (int 计数器 = 0;)
  • 我没有看到你在数组中存储任何东西,只是打印。也许您应该创建一个额外的数组,而不是在每次迭代时覆盖 line,而是存储这些值。
  • line = br.readLine() 在代码的第 2 行和第 5 行中重复,这将使您的代码在每次迭代时读取两行(这将跳过首先读取的行).. .你不需要第5行。您可以验证我的答案是否正确。
  • 您不需要添加固定代码。只需接受帮助您解决问题/问题的答案。既然你已经这样做了,一切都很好。

标签: java arrays split line


【解决方案1】:
list = Arrays.asList(line.split("\\s*,\\s*"));

这一行只是替换现有元素,所以你需要追加元素,千万不要=list变量添加元素。

这可能会有所帮助:

list.addAll(Arrays.asList(line.split("\\s*,\\s*")));

【讨论】:

    【解决方案2】:

    这应该有效:

    try {
        BufferedReader br = new BufferedReader(new FileReader("D:\\a.txt"));
        int counter = 0;
        ArrayList<String> list = new ArrayList<String>();
        for (String line; (line = br.readLine()) != null;) {
            counter++;
    
            if (counter > 51) {
                line = line.trim();
                list.addAll(Arrays.asList(line.split("\\s*,\\s*")));
            }
        }
    
        String[] array = new String[list.size()];
        array = list.toArray(array);
    
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    } catch(Exception e) {
        System.out.println(e);
    }
    

    【讨论】:

    • 谢谢!这成功了。唯一的事情是我需要输出一个字符串数组。 String[] 数组 = list.toArray(new String[list.size()]);给出 NullPointerException。有什么想法吗?
    • @Camelaria 看看我的回答,它展示了如何将List 转换为您的用例的数组。
    • 试试这个。字符串[] 数组= 新字符串[list.size()];数组 = list.toArray(array);这应该会有所帮助。
    • 您没有初始化列表,这就是 Nullpointer 的原因。做这个。 List list = new ArrayList();
    • 酷,祝你好运使用 Java。每当您发现任何有用的答案/评论时,请点赞,以便其他用户知道正确的答案。
    【解决方案3】:

    你应该尝试使用它。

        private BufferedReader innerReader;
    public List<String> loadFrom(Reader reader)
            throws IOException {
        if(reader == null)
        {
            throw new IllegalArgumentException("Reader not found");
        }
            this.innerReader = new BufferedReader(reader);
        List<String> result = new ArrayList<String>();
        String line;
        try
        {
        while((line = innerReader.readLine()) != null)
        {
            if (line == null || line.trim().isEmpty())
                throw new IllegalArgumentException(
                        "line null");
    
            StringTokenizer tokenizer = new StringTokenizer(line, ",");
            if (tokenizer.countTokens() < 6)
                throw new IllegalArgumentException(
                        "Token number (<= 6)");
            String n1 = tokenizer.nextToken(",").trim();
            String n2 = tokenizer.nextToken(",").trim();
            String n3 = tokenizer.nextToken(",").trim();
            String n4 = tokenizer.nextToken(",").trim();
            String n5 = tokenizer.nextToken(",").trim();
            String n6 = tokenizer.nextToken(",\n\r").trim();
            StringBuilder sb = new StringBuilder();
            sb.append(n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
            result.add(sb.toString());
        }
        } catch (NoSuchElementException e) {
            throw new  IllegalArgumentException(e);
        }
        return result;
    }
    

    【讨论】:

      【解决方案4】:

      如果您使用的是 Java7,则可以使用新的 Files API 来更轻松地读取文件:

      public List<List<String>> readValuesJava7() {
        Path path = Paths.get(URI.create("/tmp/coco.txt"));
        List<String> rawLines = new ArrayList<>();
        try {
          rawLines = Files.readAllLines(path);
        } catch (IOException e) {
          e.printStackTrace();
        }
        List<List<String>> lines = new ArrayList<>();
        for (String rawLine : rawLines) {
          List<String> line = new ArrayList<>();
          for (String col : rawLine.split(","))
            line.add(col.trim());
          lines.add(line);
        }
        return lines;
      }
      

      如果您使用的是 Java8,则可以将其与新的 Streams API 结合起来,如下所示:

      public List<List<String>> readValuesJava8() {
        Path path = Paths.get(URI.create("/tmp/coco.txt"));
        Stream<String> rawLines = Stream.empty();
        try {
          rawLines = Files.lines(path);
        } catch (IOException e) {
          e.printStackTrace();
        }
        return rawLines
            .map(line -> line.split(","))
            .map(cols -> Stream.of(cols).map(String::trim).collect(Collectors.toList()))
            .collect(Collectors.toList());
      }
      

      【讨论】:

        【解决方案5】:

        您可以使用String 的二维数组来表示您正在尝试读取的表。我使用ArrayList 来读取文件,因为在到达文件末尾之前您不会知道有多少行。我将ArrayList 转换为代码示例末尾的数组。

        List<String[]> resultList = new ArrayList<String[]>();
        int counter = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        
            for (String line; (line = br.readLine()) != null;) {
                counter++;
        
                if (counter > 51) {                           // ignore the first 51 lines
                    line = br.readLine();
                    line = line.trim();
                    resultList.add(line.split("\\s*,\\s*"));
                }
            }
        }
        
        String[][] resultArray = new String[counter][6];      // convert ArrayList of String[]
        resultArray = resultList.toArray(resultArray);        // to an array
        

        输出:

        System.out.println(resultArray[0][4]); // prints 67
        System.out.println(resultArray[4][1]); // prints 20140101
        System.out.println(resultArray[6][2]); // prints 7
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-13
          • 2021-02-24
          • 1970-01-01
          • 2018-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多