I'm writing a program that dynamically updates an xml file as it is being edited. It needs an add function, delete, and save, and so far, I've gotten only the add function working properly. I've got a delete method that works when I run only that method, but not when I run the program as a whole. I don't get any exceptions or errors and I'm trying to edit the file via printwriter. It creates a new temporary file with the new xml with the deleted section and then overwrites the current .xml file. It runs flawlessly when I run only the delete method, but not when I run the program as a whole.
public static void removeFromFile(String file, String lineToRemove) { try { System.out.println("Removing:\t" + lineToRemove); File inFile = new File(file); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String text = ""; Scanner sc = new Scanner(inFile); while(sc.hasNext()) { text+=sc.nextLine() + "\n"; } //System.out.println(text); text = text.replace(lineToRemove + "\n", ""); sc.close(); sc = new Scanner(text); while(sc.hasNext()) pw.println(sc.nextLine()); pw.flush(); pw.close(); sc.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); System.out.println("IO Exception: " + ex.getMessage()); } }