Do not delete the txt file

0

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);
}
    
asked by Pau Bacardit Agset 23.06.2018 в 18:06
source

1 answer

0

Hi, I've been doing tests with your static DeleteContainerLine () method and I do not see any problems with the deletion. You can check it with an impression of the boolean response of the method, since if the statement 'inputFile.delete ()' does not work the output would be 'false'.

System.out.println(Test.DeleteContainerLine(new File("src/test.txt"), "Carlos"));

I tried it creating a .txt with a line that contains the word Carlos .

    
answered by 23.06.2018 в 18:25