I am working on a project that has a method that reads a file, finds a a string that is passed in writes a new file called temp (that doesnt have the passed in line in it) and then deletes the original and renames temp to the opriginal name. I can run it without errors but it outputs nothing into the new file. I have done the usually debugging and found that the error lies in the lines where it writes out the line to the new file. I feel like I have made a small error calling something wrong. Any help solving it would be great…
Here is the code
public static void LineDelete(String Filename, String Content) throws IOException {
try {
File flights = new File("AppData/" + Filename);
File temp;
temp = new File("AppData/temp.txt");
FileWriter fstream;
BufferedWriter out;
try (Scanner sc = new Scanner(flights)) {
fstream = new FileWriter("AppData/temp.txt", true);
out = new BufferedWriter(fstream);
boolean exis = temp.exists();
if (exis) {
temp.delete();
temp = new File("AppData/temp.txt");
boolean createNewFile = temp.createNewFile();
} else {
boolean creatNewFile = temp.createNewFile();
}
String f;
while (sc.hasNextLine()) {
f = sc.nextLine();
if (!f.equals(Content)) {
out.newLine();
out.write(f);
}
}
}
fstream.close();
//out.close();
flights.delete();
File flightsn = new File("AppData/" + Filename);
temp.renameTo(flightsn);
} catch (FileNotFoundException ex) {
Logger.getLogger(FileWrite.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
You should call close on
out(BufferedReader).You should also close it in the finally clause in try-catch-finally.
Your code should be more or less