逐个字符地将文本文件读入Java中的2D数组中

时间:2015-08-02 01:45:07

标签: java arrays text-files tui

作为我的面向对象课程的一部分,我们将设计一个使用TUI最终实现GUI的战舰游戏。 根据设计,我们将从一个类似于b的文本文件中读取AI的船舶位置

 ABCDEFGHIJ
1
2 BBBB
3
4       C
5D      C
6D
7AAAAA
8     SSS  
9
0

字母代表不同的船只。我目前对游戏的实现使用了二维字符数组,因此我希望能够读取文本文件并创建相应的2D数组。我已经看到一些内置函数允许你读取下一个字符串或下一个整数,但我只想逐个字符地阅读它。有没有办法做到这一点? 提前致谢!

5 个答案:

答案 0 :(得分:3)

在我看来,最简单的方法是首先逐行读取文件,然后逐个字符地读取这些行。通过使用内置实用程序,您可以避免处理新行的复杂性,因为它们因操作系统/编辑器而异。

BufferedReader Docs

>>> list2 = [1, 2, 3]
>>> list2
[1, 2, 3]
>>> len(list2)
3
>>> str(list2)
'[1, 2, 3]'
>>> len(str(list2))
9
>>> list2[1:-1]
[2]
>>> len(list2[1:-1])
1
>>> str(list2)[1:-1]
'1, 2, 3'
>>> len(str(list2)[1:-1])
7

答案 1 :(得分:2)

看看这里。你可以通过这种方式逐字逐句阅读。你需要知道新的线条。 http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html

答案 2 :(得分:1)

//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。

答案 3 :(得分:1)

@JudgeJohn的答案很好 - 我会发表评论,但不幸的是我不能。逐行读取将确保任何系统细节(如换行符的实现)由Java的各种库处理,这些库知道如何做得很好。在文件上的某种读取器上使用Scanner可以轻松地对行进行枚举。在此之后,按字符读取获得的String字符应该不是问题,例如使用toCharArray()方法。

一个重要的补充 - 当使用StreamReader个对象以及Scanner对象时,通常很重要的是您的代码能很好地处理流程的结束 - 处理文件句柄等系统资源。这是使用这些类的close()方法在Java中完成的。现在,如果我们完成阅读并且只是调用close(),那么在计划事情时这一切都很好,但可能会抛出异常,导致方法在{{1}之前退出调用方法。一个好的解决方案是close()try - catch块。 E.g。

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. } 块如何退出,始终会调用finally块。更好的是,Java中存在try-with-resources块,如下所示:

try

这个检查所有空值,try (Scanner scanner = new Scanner(myFileStream)) { //use scanner to read through file } 和调用finally。非常安全,快速打字!

答案 4 :(得分:1)

您可以使用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