Write a file containing the contents of an array

0

I have an array of char grid and I want to write a file with its contents. Here is the code I did:

public static String getGrid() {
    String text = String.valueOf(grid);
    return text;
}


public static void Escreve() {

    String imprime = getGrid();
    System.out.println(imprime);

    File newFile = new File("C:/Users/Miguel/Desktop/newFile.txt");
    if (newFile.exists()) {
        System.out.println("já existe");
    } else {
        try {
            newFile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            FileWriter fileW = new FileWriter(newFile);
            BufferedWriter buffW = new BufferedWriter(fileW);
            buffW.write(imprime);
            buffW.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

The array grid would originally look like this:

grid = {{'W','S','W', 'W'}, {'W','W','_','E'}}

The desired end result of the created file is:

WSWW
WW_E

The first "function" transforms the array from char to string array and the second creates a new file and should write the contents of the array, but what I get in the created file is as follows: [[C @ 2424d3cc < p>

Some way to solve the problem?

    
asked by anonymous 17.06.2017 / 23:45

1 answer

1

As this is an array that stores other arrays of type char , this shape will not work. You will need to transform the innermost arrays into a string, and then save it to the file.

See your code in an example with the modifications:

public static void Escreve() {

    char[][] grid = { { 'W', 'S', 'W', 'W' }, { 'W', 'W', '_', 'E' } };

    File newFile = <caminho do arquivo>;

    if (newFile.exists()) {

        System.out.println("já existe");

    } else {

        try {
            newFile.createNewFile();
            FileWriter fileW = new FileWriter(newFile);
            BufferedWriter buffW = new BufferedWriter(fileW);

            for (char[] g : grid) {
                buffW.write(String.valueOf(g) + System.getProperty("line.separator"));
            }

            buffW.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

The output in the text file is:

WSWW
WW_E

Notice that in addition to the loop, I used System.getProperty("line.separator") to break the line, as shown in your example, regardless of the operating system run.

    
18.06.2017 / 00:38