Search code examples
javaarraylisttextfilewriter

writing text on a txt file and ways to do it


So im doing MOOC exercises right now and it asks me to write a text on a txt file using a ArrayList. I just dont understand why it accepted this code:

public void save(String file, List<String> texts) throws IOException {
        FileWriter f = new FileWriter(file, true);
        for (int i = 0; i < texts.size(); i++) {
            f.write(texts.get(i) + "\n");
        }
        f.close();
        }

but not this code:

public void save(String file, List<String> texts) throws IOException {
        FileWriter f = new FileWriter(file, true);
        for (String text : texts) {
            f.write(text);
            System.out.println("");
        }
        f.close();
    }

Solution

  • Try also writing a line separator in 2nd code as :

    for (String text : texts) {
         f.write(text);
         f.write(System.lineSeparator());
    }
    

    As mentioned in the comments, System.out.println writes to the console instead