0

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.

2
  • hard to say anything if you don't tell what does getTitleRow() produce Commented Apr 13, 2022 at 19:37
  • getTitleRow() just gets the headerRow list through a setTitleRow(), but all that does is get and set without changing anything. Commented Apr 13, 2022 at 19:42

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.