Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-4042

"java.nio.Files#delete" should be preferred

    XMLWordPrintable

    Details

    • Message:
      Use "java.nio.file.Files#delete" here for better messages on error conditions.
    • Highlighting:
      Hide

      Use of File#delete

      Show
      Use of File#delete
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      When java.io.File#delete fails, this boolean method simply returns false with no indication of the cause. On the other hand, when java.nio.file.Files#delete fails, this void method returns one of a series of exception types to better indicate the cause of the failure. And since more information is generally better in a debugging situation, java.nio.file.Files#delete is the preferred option.

      Noncompliant Code Example

      public void cleanUp(Path path) {
        File file = new File(path);
        if (!file.delete()) {  // Noncompliant
          //...
        }
      }
      

      Compliant Solution

      public void cleanUp(Path path) throws NoSuchFileException, DirectoryNotEmptyException, IOException {
        Files.delete(path);
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: