Delete a file in Java

    0

    8

    file

    Delete a file or a directory in Java. Directory must not be empty.

    import java.io.IOException;
    import java.nio.file.*;
    
    try {
      Files.deleteIfExists(Paths.get("filepath"));
    }
    catch(NoSuchFileException e)
    {
      // file does not exists
    }
    catch(DirectoryNotEmptyException e)
    {
      // attempt to delete a directory that is not empty
    }
    catch(IOException e)
    {
      // other issues (such as permissions)
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.