0

Here is my code. Everything works except the last two lines. I am trying to remove a line from a .txt and rewrite the file into a tempfile and then rename the tempfile to original. The last two lines are being ignored though. Here is what the error is:

https://i.gyazo.com/66a320aeaf487837ce64fe3424074de6.png

These two lines are being ignored:

inputFile.delete();

tempFile.renameTo(inputFile);

File inputFile = new File(a.getDirectoryData() + "UserTwo.txt");
File tempFile = new File(a.getDirectoryData() + "TempUserTwo.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;

while((currentLine = reader.readLine()) != null) {
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(a.username + ":" + a.password)) continue;
    writer.write(currentLine + "\r\n");

}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    Possible duplicate of [Rename a file using Java](https://stackoverflow.com/questions/1158777/rename-a-file-using-java) – nagendra547 Sep 04 '17 at 17:24
  • That's not really an error. It's a code inspection that's saying the functions .delete() and .renameTo() return a value that indicates success or failure. You are ignoring that return value. What if the .delete() fails because of a sharing violation or what if the .renameTo() fails because you are trying to rename to an existing file. You're not checking for those. – JJF Sep 04 '17 at 17:26
  • I added this line of code and it still didn't work. if (inputFile.exists()) { inputFile.delete(); } – joeybots59 Sep 04 '17 at 17:34

1 Answers1

0

Looks like it cannot delete a file. Can you try to use

Files.delete(inputFile.toPath()) 

instead?

From docs:

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

andrey4623
  • 81
  • 6