Search code examples
javaarraystext-filestui

Reading a text file character by character into a 2D array in Java


As part of my Object Oriented class, we are to design a Battleship game which uses a TUI to eventually implement a GUI. According to the design, we are to read the AI's ship locations from a text file that will look similar to the one b

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

Where the letters represent different ships. My current implementation of the game uses a 2 dimensional array of characters, so I would like to be able to read the text file and create the corresponding 2D array. I've seen a few built in functions that allow you to read the next String or the next Integer, but I just want to read it character by character. Is there a way to do this? Thanks in advance!


Solution

  • The simplest way to do this, in my opinion, is to first read the file line-by-line then read those lines character-by-character. By using a built-in utility, you can avoid the complexities of handling new lines because they vary by OS/Editor.

    BufferedReader Docs

        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();