Truncating the file count deletes any files with ids at or above the
new count.
6928
public void truncateFileCount(long count) throws IOException {
        if (count < 0) {
            throw new IllegalArgumentException("count < 0: " + count);
        }
        try {
            mFileTableLock.acquireUpgradableLock();
            long oldCount = getFileCount();
            if (count >= oldCount) {
                return;
            }
            
            mFileTableLock.acquireWriteLock();
            try {
                for (long id = oldCount; --id >= count; ) {
                    deleteFile(id);
                }
                mFileTable.truncate(count * mFileTableEntrySize);
            }
            finally {
                mFileTableLock.releaseLock();
            }
        }
        catch (InterruptedException e) {
            throw new InterruptedIOException();
        }
        finally {
            mFileTableLock.releaseLock();
        }
    }
562683
protected function deleteOldFiles()
    {
        $repository = new DashboardRepository();

        $files = $repository->getFiles();
        $items = [];

        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            $items[$file->getMTime()] = $file;
        }

        krsort($items);

        $i = 0;

        /** @var \SplFileInfo $file */
        foreach ($items as $file) {
            $i++;

            if ($i < 100) {
                continue;
            }

            File::delete($file->getPathname());
        }
    }
599307
public static function removeOldFiles() {
		
		if (!is_dir(static::TEMP_FOLDER)) {
			return;
		}
		
		$app = Application::getInstance();
		$counter = 0;

		$files = Utilities::getDirectoryFilenames(static::TEMP_FOLDER);

		foreach ($files as $file) {

			$pathFile	= APPLICATION_PATH . '/' .static::TEMP_FOLDER . '/' . $file;
			$fileLife	= time() - filemtime($pathFile);
			$maxLife	= static::FILE_EXPIRE * 60;
			
			if ($fileLife > $maxLife) {
				$counter++;
				unlink($pathFile);
			}

		}
		
		if ($counter) {
			$app->logEvent($counter . ' files has been deleted from ' . static::TEMP_FOLDER);
		} else {
			$app->logEvent('No old files deleted from ' . static::TEMP_FOLDER);
		}
		
	}
1002626
protected void cleanupSfDumps(boolean deleteOldest)
  {
    // Check what the maximum number of dumpfiles and the max allowable
    // aggregate dump file size is.
    int maxDumpFiles =
        System.getProperty(MAX_NUM_DUMP_FILES_PROP) != null ?
        Integer.valueOf(System.getProperty(MAX_NUM_DUMP_FILES_PROP)) :
        DEFAULT_MAX_DUMP_FILES;

    int maxDumpDirSizeMB =
        System.getProperty(MAX_SIZE_DUMPS_MB_PROP) != null ?
        Integer.valueOf(System.getProperty(MAX_SIZE_DUMPS_MB_PROP)) :
        DEFAULT_MAX_DUMPDIR_SIZE_MB;

    File dumpDir = new File(logDumpPathPrefix);
    long dirSizeBytes = 0;

    if (dumpDir.listFiles() == null)
    {
      return;
    }

    // Keep a sorted list of files by size as we go in case we need to
    // delete some
    TreeSet<File> fileList =
        new TreeSet<>(new Comparator<File>()
        {
          @Override
          public int compare(File a, File b)
          {
            return a.length() < b.length() ? -1 : 1;
          }
        });

    // Loop over files in this directory and get rid of old ones
    // while accumulating the total size
    for (File file : dumpDir.listFiles())
    {
      if ((!file.getName().startsWith(LOG_DUMP_FILE_NAME) &&
           !file.getName().startsWith(IncidentUtil.INC_DUMP_FILE_NAME)) ||
          (System.currentTimeMillis() - file.lastModified() > FILE_EXPN_TIME_MS &&
           file.delete()))
      {
        continue;
      }

      dirSizeBytes += file.length();
      fileList.add(file);
    }

    // If we're exceeding our max allotted disk usage, cut some stuff out;
    // else if we need to make space for a new dump delete the oldest.
    if (dirSizeBytes >= ((long) maxDumpDirSizeMB << 20))
    {
      // While we take up more than half the allotted disk usage, keep deleting.
      for (File file : fileList)
      {
        if (dirSizeBytes < ((long) maxDumpDirSizeMB << 19))
        {
          break;
        }

        long victimSize = file.length();
        if (file.delete())
        {
          dirSizeBytes -= victimSize;
        }
      }
    }
    else if (deleteOldest && fileList.size() >= maxDumpFiles)
    {
      fileList.first().delete();
    }
  }
924782
def files_delete(self, *, id: str, **kwargs) -> SlackResponse:
        
        kwargs.update({"id": id})
        return self.api_call("files.delete", json=kwargs)
1018816
public static function cleanupNotRemovedFiles()
    {
        $timeOneWeekAgo = strtotime('-1 week');

        $files = _glob(self::getTmpPath() . '/*');
        if (empty($files)) {
            return;
        }

        foreach ($files as $file) {
            if (file_exists($file)) {
                $timeLastModified = filemtime($file);

                if ($timeLastModified !== false && $timeOneWeekAgo > $timeLastModified) {
                    unlink($file);
                }
            }
        }
    }
1317599
protected function deleteIgnoredFiles()
    {
        if ($this->ignore) {
            foreach ($this->phpci->ignore as $file) {
                $cmd = 'rm -Rf "%s/%s"';
                if (IS_WIN) {
                    $cmd = 'rmdir /S /Q "%s\%s"';
                }
                $this->phpci->executeCommand($cmd, $this->directory, $file);
            }
        }
    }
686726
private boolean purge(final int lowIndex, final int highIndex) {
    int suffixLength = 0;

    List renames = new ArrayList();
    StringBuffer buf = new StringBuffer();
    formatFileName(new Integer(lowIndex), buf);

    String lowFilename = buf.toString();

    if (lowFilename.endsWith(".gz")) {
      suffixLength = 3;
    } else if (lowFilename.endsWith(".zip")) {
      suffixLength = 4;
    }

    for (int i = lowIndex; i <= highIndex; i++) {
      File toRename = new File(lowFilename);
      boolean isBase = false;

      if (suffixLength > 0) {
        File toRenameBase =
          new File(
            lowFilename.substring(0, lowFilename.length() - suffixLength));

        if (toRename.exists()) {
          if (toRenameBase.exists()) {
            toRenameBase.delete();
          }
        } else {
          toRename = toRenameBase;
          isBase = true;
        }
      }

      if (toRename.exists()) {
        //
        //    if at upper index then
        //        attempt to delete last file
        //        if that fails then abandon purge
        if (i == highIndex) {
          if (!toRename.delete()) {
            return false;
          }

          break;
        }

        //
        //   if intermediate index
        //     add a rename action to the list
        buf.setLength(0);
        formatFileName(new Integer(i + 1), buf);

        String highFilename = buf.toString();
        String renameTo = highFilename;

        if (isBase) {
          renameTo =
            highFilename.substring(0, highFilename.length() - suffixLength);
        }

        renames.add(new FileRenameAction(toRename, new File(renameTo), true));
        lowFilename = highFilename;
      } else {
        break;
      }
    }

    //
    //   work renames backwards
    //
    for (int i = renames.size() - 1; i >= 0; i--) {
      Action action = (Action) renames.get(i);

      try {
        if (!action.execute()) {
          return false;
        }
      } catch (Exception ex) {
        LogLog.warn("Exception during purge in RollingFileAppender", ex);

        return false;
      }
    }

    return true;
  }
432810
@Initialize(distributed = false)
    public void truncateIfNecesary() {
        if (truncateTable) {
            final UpdateableDatastoreConnection con = datastore.openConnection();
            try {
                final SchemaNavigator schemaNavigator = con.getSchemaNavigator();

                final Table table = schemaNavigator.convertToTable(schemaName, tableName);

                final UpdateableDataContext dc = con.getUpdateableDataContext();
                dc.executeUpdate(new UpdateScript() {
                    @Override
                    public void run(UpdateCallback callback) {
                        final RowDeletionBuilder delete = callback.deleteFrom(table);
                        if (logger.isInfoEnabled()) {
                            logger.info("Executing truncating DELETE operation: {}", delete.toSql());
                        }
                        delete.execute();
                    }
                });
            } finally {
                con.close();
            }
        }
    }
1217079
protected void objectsRemoved(DBIDs ids) {
    final Logging log = getLogger();
    StepProgress stepprog = log.isVerbose() ? new StepProgress(3) : null;

    // delete the materialized (old) kNNs
    log.beginStep(stepprog, 1, "New deletions ocurred, remove their materialized kNNs.");
    for(DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) {
      storage.delete(iter);
    }

    // update the affected kNNs
    log.beginStep(stepprog, 2, "New deletions ocurred, update the affected kNNs.");
    ArrayDBIDs rkNN_ids = updateKNNsAfterDeletion(ids);

    // inform listener
    log.beginStep(stepprog, 3, "New deletions ocurred, inform listeners.");
    fireKNNsRemoved(ids, rkNN_ids);

    log.ensureCompleted(stepprog);
  }
605205
protected function _truncate()
    {
        if (!$this->getLimit()->isNull()) {
            if (is_null($this->getLimit()->getCount())) {
                $this->_output = array_splice($this->_output, $this->getLimit()->getStart());
            } else {
                $this->_output = array_splice($this->_output, $this->getLimit()->getStart(), $this->getLimit()->getCount());
            }
        }
    }
242915
public void cleanup() {
        if (file != null && file.exists() && !file.delete()) {
            LOGGER.debug("Failed to delete first temporary file {}", file.toString());
            file.deleteOnExit();
        }
    }
1337692
private void groomTruncationSnapshots() {
        ArrayList<TruncationSnapshotAttempt> toDelete = new ArrayList<TruncationSnapshotAttempt>();
        boolean foundMostRecentSuccess = false;
        Iterator<Map.Entry<Long, TruncationSnapshotAttempt>> iter =
            m_truncationSnapshotAttempts.descendingMap().entrySet().iterator();
        loggingLog.info("Snapshot daemon grooming truncation snapshots");
        while (iter.hasNext()) {
            Map.Entry<Long, TruncationSnapshotAttempt> entry = iter.next();
            TruncationSnapshotAttempt snapshotAttempt = entry.getValue();
            if (!foundMostRecentSuccess) {
                if (snapshotAttempt.finished) {
                    loggingLog.info("Found most recent successful snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                            + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                    foundMostRecentSuccess = true;
                } else {
                    loggingLog.info("Retaining possible partial snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                            + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                }
            } else {
                loggingLog.info("Deleting old unecessary snapshot txnid " + TxnEgo.txnIdToString(entry.getKey())
                        + " path " + entry.getValue().path + " nonce " + entry.getValue().nonce);
                toDelete.add(entry.getValue());
                iter.remove();
            }
        }

        String paths[] = new String[toDelete.size()];
        String nonces[] = new String[toDelete.size()];

        int ii = 0;
        for (TruncationSnapshotAttempt attempt : toDelete) {
            paths[ii] = attempt.path;
            paths[ii] = SnapshotUtil.getRealPath(SnapshotPathType.valueOf(attempt.pathType), paths[ii]);
            nonces[ii++] = attempt.nonce;
        }

        Object params[] =
            new Object[] {
                paths,
                nonces,
                SnapshotPathType.SNAP_CL.toString()
                };
        long handle = m_nextCallbackHandle++;
        m_procedureCallbacks.put(handle, new ProcedureCallback() {

            @Override
            public void clientCallback(ClientResponse clientResponse)
                    throws Exception {
                if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
                    SNAP_LOG.error(clientResponse.getStatusString());
                }
            }

        });
        m_initiator.initiateSnapshotDaemonWork("@SnapshotDelete", handle, params);
    }
862946
public void truncate(int newsize) {
    if(newsize < size) {
      double[] odists = dists;
      dists = new double[newsize];
      System.arraycopy(odists, 0, dists, 0, newsize);
      int[] oids = ids;
      ids = new int[newsize];
      System.arraycopy(oids, 0, ids, 0, newsize);
      size = newsize;
    }
  }
1244705
@Override
    public void deleteAll(final String... ids) {
        if (ids == null || ids.length == 0) {
            return;
        }

        // process ids in groups of <partition size>
        final ArrayList<String> list = Lists.newArrayList(ids);
        for (final List<String> partition : Lists.partition(list, config.getPartitionSize())) {
            doDeleteAllIds(partition);
            for (final String id : partition) {
                notifyDeleted(id);
            }
        }
    }
1014235
private void cleanupBackupDir(int keep) {
        File[] backupDirFiles = getSortedBackupDirFiles();
        if (backupDirFiles.length > keep) {
            for (int i = keep; i < backupDirFiles.length; i++) {
                backupDirFiles[i].delete();
            }
        }
    }
1360714
private Method reflectTruncate(FileSystem fs) {
		// completely disable the check for truncate() because the check can be problematic
		// on some filesystem implementations
		if (!useTruncate) {
			return null;
		}

		Method m = null;
		if (fs != null) {
			Class<?> fsClass = fs.getClass();
			try {
				m = fsClass.getMethod("truncate", Path.class, long.class);
			} catch (NoSuchMethodException ex) {
				LOG.debug("Truncate not found. Will write a file with suffix '{}' " +
					" and prefix '{}' to specify how many bytes in a bucket are valid.", validLengthSuffix, validLengthPrefix);
				return null;
			}

			// verify that truncate actually works
			Path testPath = new Path(basePath, UUID.randomUUID().toString());
			try {
				try (FSDataOutputStream outputStream = fs.create(testPath)) {
					outputStream.writeUTF("hello");
				} catch (IOException e) {
					LOG.error("Could not create file for checking if truncate works.", e);
					throw new RuntimeException(
							"Could not create file for checking if truncate works. " +
									"You can disable support for truncate() completely via " +
									"BucketingSink.setUseTruncate(false).", e);
				}

				try {
					m.invoke(fs, testPath, 2);
				} catch (IllegalAccessException | InvocationTargetException e) {
					LOG.debug("Truncate is not supported.", e);
					m = null;
				}
			} finally {
				try {
					fs.delete(testPath, false);
				} catch (IOException e) {
					LOG.error("Could not delete truncate test file.", e);
					throw new RuntimeException("Could not delete truncate test file. " +
							"You can disable support for truncate() completely via " +
							"BucketingSink.setUseTruncate(false).", e);
				}
			}
		}
		return m;
	}