Java: txt 文件到第二个数组
Java: txt file into a 2nd array
所以,第一个问题是如何从文件 txt 中获取列数。
文件是这样的:
WWWSWW\n
WWW___\n
WWWWWW\n
W_____\n
WWW_WW\n
W_____\n
W_W_W\n
WE____\n
在此示例中,我有 8 行和 8 列,但我必须从文件中提取它。
另一个问题是我不能 return 数组到另一个 class。
我的代码:
File file = new File("maze.txt");
Scanner scanner = new Scanner(file);
//contar as linhas
List<String> lines=
Files.readAllLines(Paths.get("maze.txt"),Charset.defaultCharset());
int noOfLines=lines.size()-1;
char[][] myArray=new char[noOfLines][noOfLines];
//this read the file and make the array
for (int row = 0; scanner.hasNextLine() && row < noOfLines; row++) {
char[] chars = scanner.nextLine().toCharArray();
for (int i = 0; i < noOfLines && i < chars.length; i++) {
myArray[row][i] = chars[i];
}
}
我会像你一样阅读整个文件,然后使用 Java 8 的流媒体功能为你完成所有繁重的工作:
char[][] maze = lines.stream().map(String::toCharArray).toArray(char[][]::new);
所以,第一个问题是如何从文件 txt 中获取列数。 文件是这样的:
WWWSWW\n
WWW___\n
WWWWWW\n
W_____\n
WWW_WW\n
W_____\n
W_W_W\n
WE____\n
在此示例中,我有 8 行和 8 列,但我必须从文件中提取它。
另一个问题是我不能 return 数组到另一个 class。
我的代码:
File file = new File("maze.txt");
Scanner scanner = new Scanner(file);
//contar as linhas
List<String> lines=
Files.readAllLines(Paths.get("maze.txt"),Charset.defaultCharset());
int noOfLines=lines.size()-1;
char[][] myArray=new char[noOfLines][noOfLines];
//this read the file and make the array
for (int row = 0; scanner.hasNextLine() && row < noOfLines; row++) {
char[] chars = scanner.nextLine().toCharArray();
for (int i = 0; i < noOfLines && i < chars.length; i++) {
myArray[row][i] = chars[i];
}
}
我会像你一样阅读整个文件,然后使用 Java 8 的流媒体功能为你完成所有繁重的工作:
char[][] maze = lines.stream().map(String::toCharArray).toArray(char[][]::new);