[英]Reading a text file character by character into a 2D array in Java
作为我的面向对象类的一部分,我们将设计一个战舰游戏,该游戏使用TUI最终实现GUI。 根据设计,我们将从文本文件中读取AI的飞船位置,该文本文件看起来类似于一个
ABCDEFGHIJ 1 2 BBBB 3 4 C 5D C 6D 7AAAAA 8 SSS 9 0
字母代表不同的船。 我当前的游戏实现使用二维字符数组,因此我希望能够读取文本文件并创建相应的2D数组。 我已经看到了一些内置函数,这些函数允许您读取下一个String或下一个Integer,但是我只想逐个字符地读取它。 有没有办法做到这一点? 提前致谢!
我认为,最简单的方法是先逐行读取文件,然后逐字符读取这些行。 通过使用内置实用程序,您可以避免处理新行的复杂性,因为它们会因OS / Editor而异。
BufferedReader fileInput = new BufferedReader(new FileReader("example.txt"));
String s;
while ((s = fileInput.readLine()) != null) {
for (char c : s.toCharArray()) {
//Read into array
}
}
fileInput.close();
在这里看看。您可以通过这种方式逐字阅读。 您需要注意新行。 http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html
//Open file stream
FileReader in = new FileReader("fileName.txt");
BufferedReader br = new BufferedReader(in);
String line = ""; //Declare empty string used to store each line
//Read a single line in the file and store it in "line" variable
//Loop as long as "line" is not null (end of file)
while((line = br.readLine() != null) {
//Iterate through string until the end
//Can use a regular loop also
for(char ch : line.toCharArray()) {
//Do something with the variable ch
if(ch == 'B')
;
else if(ch == 'C')
;
else if(ch == ' ')
;
else
;
}
}
总体思路是将问题分解为更简单的解决方案。 如果您具有可以打开文件并读取一行的功能,则可以解决一个问题。 接下来,您需要解决一个字符一个字符地迭代的问题。 这可以通过多种方法完成,但是一种方法是使用String类的内置函数将String转换为字符数组。
唯一缺少的是打开文件以及正确导入类时通常需要的try {} catch {}:FileReader和BufferedReader。
@JudgeJohn的回答很好-我会发表评论,但我不能不幸。 逐行阅读将确保Java的各种库处理任何系统详细信息(如换行符的实现),它们都知道如何做到这一点。 在文件的某种读取器上使用Scanner
,可以轻松枚举行。 此后,例如,使用toCharArray()
方法,按字符读取获得的String
字符应该不会成为问题。
一个重要的补充-使用Stream
和Reader
对象以及Scanner
对其进行处理时,很重要的一点是,您的代码必须很好地处理过程的结尾-处置系统资源(如文件句柄)。 这是使用这些类的close()
方法在Java中完成的。 现在,如果我们完成阅读并仅调用close()
,那么当事情按计划进行时,一切都很好,但是有可能会抛出异常,从而导致该方法在调用close()
方法之前退出。 一个好的解决方案是try - catch
还是try - finally
阻止。 例如
Scanner scanner = null;
try {
scanner = new Scanner(myFileStream);
//use scanner to read through file
scanner.close();
} catch (IOException e) {
if (scanner != null) scanner.close(); //check for null in case scanner never got initialised.
}
更好的是
Scanner scanner = null;
try {
scanner = new Scanner(myFileStream);
//use scanner to read through file
} finally {
if (scanner != null) scanner.close(); //check for null in case scanner never got initialised.
}
无论try
块如何退出,始终都会调用finally
块。 更好的是,Java中有一个try-with-resources块,如下所示:
try (Scanner scanner = new Scanner(myFileStream)) {
//use scanner to read through file
}
这将检查所有空值, finally
再调用close()
。 非常安全,打字快捷!
您可以使用Scanner
来读取单个字符,如下所示:
scanner.findInLine(".").charAt(0)
木板是一个11x11的字符( char[][] board = new char[11][11]
),因此在读取字符时,您必须跟踪所处的行和列。 阅读第11个字符后,您将知道何时进入下一行。
代码示例:
public static void main(String[] args) throws Exception {
String file =
" ABCDEFGHIJ\n" +
"1 \n" +
"2 BBBB \n" +
"3 \n" +
"4 C \n" +
"5D C \n" +
"6D \n" +
"7AAAAA \n" +
"8 SSS \n" +
"9 \n" +
"0 \n";
char[][] board = new char[11][11];
Scanner scanner = new Scanner(file);
int row = 0;
int col = 0;
while (scanner.hasNextLine()) {
// Read in a single character
char character = scanner.findInLine(".").charAt(0);
board[row][col] = character;
col++;
if (col == 11) {
// Consume the line break
scanner.nextLine();
// Move to the next row
row++;
col = 0;
}
}
// Print the board
for (int i = 0; i < board.length; i++) {
System.out.println(new String(board[i]));
}
}
结果:
ABCDEFGHIJ
1
2 BBBB
3
4 C
5D C
6D
7AAAAA
8 SSS
9
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.