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
        }
    }
4

2 回答 2

2

您需要在打开 FileWriter 之前关闭扫描仪,以避免文件冲突。

    ...
    read.close();
    FileWriter fw = new FileWriter(file,false);
    for (String itemFile1 : itemFile) {
        fw.write(itemFile1);
        fw.write(System.lineSeparator()); //new line
    }
    fw.close();
于 2015-05-22T18:11:40.427 回答
0

我相信有一个错字。在最后一个 for 循环中,当您的变量名称为 fw 时,您有 fwp.write(...)。这可能是问题所在。

于 2015-05-22T18:07:29.057 回答