0

With this code I want to read one text file, put all elements into a arraylist and replace the file with the the arraylist contain. But this code don't write into file and I don't know why...

public void delete(String lineToDelete, String nameFile) throws IOException {
        file = new File(nameFile);
        fw = new FileWriter(file,false);

        read = new Scanner(file);
        while (read.hasNext()) {
            itemFile.add(read.nextLine());
        }
        for (int i = 0; i < itemFile.size(); i++) {
            if (itemFile.get(i).equals(lineToDelete)) {
                itemFile.remove(i);
                break;
            }
        }
        for (String itemFile1 : itemFile) {
            fw.write(itemFile1);
            fw.write(System.lineSeparator()); //new line
        }
    }
Pshemo
  • 122,468
  • 25
  • 185
  • 269
cavaler12345
  • 367
  • 1
  • 5
  • 15

2 Answers2

2

You need to close your scanner before opening your FileWriter, to avoid conflicts on the file.

    ...
    read.close();
    FileWriter fw = new FileWriter(file,false);
    for (String itemFile1 : itemFile) {
        fw.write(itemFile1);
        fw.write(System.lineSeparator()); //new line
    }
    fw.close();
JP Moresmau
  • 7,388
  • 17
  • 31
0

I believe theres a typo. In the last for loop you have fwp.write(...) when your variable's name is fw. This could be the problem.