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 } } 
7
  • Does it throw any errors? Have you tried to step through your code, either with a debugger or by print statements? Commented May 22, 2015 at 18:04
  • Nop... I don't have any errors.. Commented May 22, 2015 at 18:05
  • 1
    Redundant java tags are unnecessary. What about this code requires a specific version? Commented May 22, 2015 at 18:05
  • 3
    Try closing/flushing your streams/writers. Commented May 22, 2015 at 18:05
  • the itemfile is a arraylist where I put all my file, and after that i try to put the contain in the same text file Commented May 22, 2015 at 18:06

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.