I'm trying to make a program that deletes a player from the ones in a txt file, so I create a tmp file and then I want to erase the original and rename the tmp with the name of the original.
private static void DeletePlayer(File f){
System.out.println("Player Name:");
String name = keyboard.next();
boolean contains = false;
for(List<Player> lp : map.values()){
for(Player p : lp){
if(p.getName().equals(name)){
contains = true;
break;
}
}
}
if(!contains){
System.out.println("Selected player does not exists");
return;
}
try{
DeleteContainerLine(f, name);
}catch(IOException e){
e.printStackTrace();
}
}
private static boolean DeleteContainerLine(File f, String name) throws FileNotFoundException, IOException{
File inputFile = f;
File tempFile = new File(f.getAbsolutePath() + ".tmp");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null){
if(!currentLine.contains(name)){
writer.write(currentLine);
}
}
writer.close();
reader.close();
return inputFile.delete() && tempFile.renameTo(inputFile);
}