When I try to rename “newfile” to “dump” it says it cannot change the file name. The file exists and it is able to be written to. Here is the code:
String name = "C:/Users/ajmer/OneDrive/Desktop/formation1/src/savedata.txt";
String name1= "C:/Users/ajmer/OneDrive/Desktop/formation1/src/temp.txt";
long count= Files.lines(Paths.get(name)).count();
Scanner scanner= new Scanner(System.in);
Scanner readlines = new Scanner(name);
FileWriter savedata = new FileWriter(name, true);
PrintWriter writer = new PrintWriter(savedata);
Homework homework1= new Homework("empty","2024-08-24" );
//LocalDate.now()
System.out.println("Enter the due date of the homework: YYYY-MM-DD");
homework1.dueDate= scanner.nextLine();
//LocalDate.parse
while(homework1.dueDate!="done"){
writer.println(homework1.dueDate);
break;
}
while(homework1.dueDate.equals("done")){
try{
File oldfile = new File(name);
File newfile = new File(name1);
int line=0;
String currentline;
FileWriter fw= new FileWriter(name1, true);
BufferedWriter bw =new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
FileReader fr= new FileReader(name);
BufferedReader br = new BufferedReader(fr);
while((currentline=br.readLine())!=null){
line++;
if((count)!=line){
pw.println(currentline);
}
}
pw.flush();
pw.close();
br.close();
fw.close();
bw.close();
fr.close();
oldfile.delete();
File dump=new File(name);
if (newfile.renameTo(dump)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Error renaming the file.");
System.out.println("Old file exists: " + oldfile.exists());
System.out.println("New file exists: " + newfile.exists());
System.out.println("Can write to old file: " + oldfile.canWrite());
System.out.println("Can write to new file: " + newfile.canWrite());
}
}catch (IOException c){
c.printStackTrace();
}
System.exit(0);
}
I tried deleting the temp.txt file hoping the file existing was the problem but nothing changed. I also tried using Files.move() but could not figure out what was making an error.
New contributor
Natalie Ajmeri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.