I am having trouble editing a record in a text file in Java. I am able to print to the temporary file, but am unable to delete the main file and rename the temporary file.
private void editFile(String old, String newLine) throws FileNotFoundException, IOException {
try {
File inFile = new File ("Members.txt");
File tempFile = new File ("Members_Temp.txt");
inFile.setReadable(true);
inFile.setWritable(true);
tempFile.setReadable(true);
tempFile.setWritable(true);
PrintWriter PW;
try (
//Defines the BufferedReader to read the Current File
BufferedReader BR = new BufferedReader(new FileReader(inFile))) {
FileWriter temp = new FileWriter(tempFile);
PW = new PrintWriter (temp);
String line = null;
//While Loop to read the current file till it ends
while ((line = BR.readLine()) != null) {
String replace = old.replace(old, newLine); //Replaces old data with the new data
PW.write(replace); //Writes to the temporary file
//PW.flush();
}
BR.close();
PW.close();
inFile.delete();
tempFile.renameTo(inFile);
}
}
catch (IOException ex) {
}
}
I have tried swapping the statements around but that doesn't see to work either. I was considering the Files.move statement but am unsure on how to use it? The files are found within the program folder, and I plan on making it portable so the directories will be different when the program is used on a different computer, hence why I thought the paths would be different each time.