Java File Delete nio delete(File file)

Here you can find the source of delete(File file)

Description

delete

License

Apache License

Declaration

public static void delete(File file) throws IOException 

Method Source Code

//package com.java2s;
/*/* w  ww  .  j av  a 2s.  c  om*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.IOException;

import java.nio.file.AccessDeniedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;

import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.Uninterruptibles;

public class Main {
    public static void delete(File file) throws IOException {
        for (int n = 0; n < 10; n++) {
            try {
                Files.delete(file.toPath());
                if (Files.exists(file.toPath())) {
                    Uninterruptibles.sleepUninterruptibly(200,
                            TimeUnit.MILLISECONDS);
                    continue;
                }
                return;
            } catch (DirectoryNotEmptyException dnee) {
                // A previous file delete operation did not finish before this call
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
                continue;
            } catch (AccessDeniedException ade) {
                // The file was locked by antivirus, indexing, or another operation triggered by previous file modification
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
                continue;
            } catch (NoSuchFileException nse) {
                return; // The file has been eventually deleted after a previous operation that failed. no-op
            }
        }
        // File could not be deleted multiple times. It is very likely locked in another process
        throw new IOException("Could not delete: " + file.toPath());
    }
}

Related

  1. delete(File f)
  2. delete(File file)
  3. delete(File file)
  4. delete(File file)
  5. delete(File file)
  6. delete(File file)
  7. delete(File file)
  8. delete(File toRecurse)
  9. delete(final File directory, final FileFilter fileFilter)