如何使用Java流直接将文本文件读取到{col,row和value}的对象数组中?

问题描述 投票:0回答:1

我需要一些指导。我不确定如何使用Java Streams将示例文本文件读入对象数组。流是否提供正确输出从文件中读取的字符(坐标)位置的功能?

我有一个对象。

public class Square {
protected int row;
protected int column;
protected char val;
protected Square(int row, int column, char val) {
....
}

}

我正在使用Java I / O读取文件,然后将内容作为字符串传递给此函数以创建Square数组...。

`public static Square[][] buildFromString(input){
        String[] lines = input.split("[\r]?\n");
        int height = lines.length;
        int width = lines[0].length();
        Square[][] squares = new Square[height][width];

        for (int row = 0; row < height; row++) {
            for (int col = 0; col < width; col++) {
                Square square = new Square(row, col, lines[row].charAt(col));
                squares[row][col] = square;
            }
        }
 ...
 }`

可以使用Java 8 Stream完成对象数组的创建吗?如果是这样,请。谢谢。

##########
#        #
# ### ## #
# #    # #
java java-8 java-stream maze
1个回答
0
投票

Java Stream不是您应该使用的。它不是I / O api。

您的选择包括:

  • 使用BufferedReader.readLine()读取行,然后使用String.split(...)将每一行拆分为字段。
  • 使用Scanner将各个字段读取为字符串,数字等。>
  • 使用解析器生成器(例如ANTLR)生成词法分析器和解析器。
  • 手动编写词法分析器/解析器。
  • 最佳(最简单)的选择取决于您的文本文件格式。

© www.soinside.com 2019 - 2024. All rights reserved.