我需要一些指导。我不确定如何使用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 Stream
不是您应该使用的。它不是I / O api。
您的选择包括:
BufferedReader.readLine()
读取行,然后使用String.split(...)
将每一行拆分为字段。Scanner
将各个字段读取为字符串,数字等。>最佳(最简单)的选择取决于您的文本文件格式。