Home > Blockchain >  How do you get BufferedWriter to remove brackets from an ArrayList when writing to a file?
How do you get BufferedWriter to remove brackets from an ArrayList when writing to a file?

Time:04-14

I have made a bufferedWriter to take an arraylist of things and comma separate them. It works well, but when I retrieve the data it starts adding extra brackets: [banana, potato, tomato, carrot] goes in and [[banana, potato, tomato, carrot]] comes out. This is the code that writes the file:

public static void writeToCSV() throws IOException {//Finds the file name.
    BufferedWriter bufferedWriter = null;
    try {
        String gameHeader = String.valueOf(getTitleRow());
        //Finds the file
        File file = new File("_GAMES/"   getSaveName()   "_"   stepped   ".csv");

        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(gameHeader);

        System.out.println("File: "   getSaveName()   " written");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bufferedWriter!=null) {
                bufferedWriter.close();
            }
        } catch (Exception ex) {
            System.out.println("Error in closing"   ex);
        }
    }
}

This is the array list:

ArrayList<String> headerRow = new ArrayList<>();
        headerRow.add(strDate);
        headerRow.add("6 x 10");
        headerRow.add("1");
        headerRow.add("6");
        headerRow.add("11");

I also use a getter/setter to move the array list between scopes:

private static ArrayList<String> titleRow =  new ArrayList<>();

public static ArrayList<String> getTitleRow() {
    return titleRow;
}

public void setTitleRow(ArrayList<String> titleRow) {
    this.titleRow = new ArrayList<>(titleRow);
}

I'm sure there is a way to use regex to replace "[" and "]" with "" but I'm not sure where to call it.

CodePudding user response:

The problem is that you use String.valueOf(list) as a way to get a comma separated list of values.

That is not good, cause the string representation of a list adds the brakets around its values: [value1, value2, value3, ...]. A better solution is to replace String.valueOf() with

String.join(",", getTitleRow()));

which yields:

2022-04-13,6 x 10,1,6,11

this is not perfect, since sometimes values require to be quoted (surrounded by " "), but it might be enough for your needs. Alternatively use a csv library like https://commons.apache.org/proper/commons-csv/.

  • Related