Hi I am having trouble deleting and renaming my file this is because my file is still open but when I try to close my file I then get a stream closed
which means my file is closed, my question how do I get my code to delete and rename my file even though my file stream is closed, all my txt files are in the correct folder
public static void updateRecord(int recordID, int recordColumnIndex, String newValue,String fileName) throws IOException {
java.io.PrintWriter writer;
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(fileName))) {
writer = new java.io.PrintWriter("temp.txt");
String line;
// Read file line by line...
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
writer.println(line);
continue;
}
// Split each read line to separate data.
String[] lineParts = line.split("\\s*,\\s*");
/* If the record ID value matches the supplied ID value
then make the desired changes to that line. */
if (Integer.parseInt(lineParts[0]) == recordID) {
lineParts[recordColumnIndex] = newValue;
// Rebuild the data line...
StringBuilder sb = new StringBuilder(String.valueOf(recordID));
for (int i = 1; i < lineParts.length; i++) {
sb.append(",").append(lineParts[i]);
}
line = sb.toString();
}
writer.println(line); // write line to `temp.tmp` file.
writer.flush(); // Immediate write.
reader.close();
}
}
writer.close();
File inputFile = new File("tasks.txt");
File outFile = new File("temp.txt");
if (inputFile.exists()) {
Files.delete(Path.of("tasks.txt"));
outFile.renameTo(inputFile);
System.out.println("test");
}else{
System.out.println("error");
}
}