Copy the contents of the logfile to another file. Truncate the logfile
 to zero length. This method will set the roll flag so that all the
 current logfiles will be rolled along with the copied file.
768451
def copy_truncate
      return unless ::File.exist?(@fn)
      FileUtils.concat @fn, @fn_copy
      @io.truncate 0

      # touch the age file if needed
      if @age
        FileUtils.touch @age_fn
        @age_fn_mtime = nil
      end

      @roller.roll = true
    end
648525
@Override
  public void truncate(Zxid zxid) throws IOException {
    try (SimpleLogIterator iter = new SimpleLogIterator(this.logFile)) {
      this.lastSeenZxid = Zxid.ZXID_NOT_EXIST;
      while (iter.hasNext()) {
        Transaction txn = iter.next();
        if (txn.getZxid().compareTo(zxid) == 0) {
          this.lastSeenZxid = txn.getZxid();
          break;
        }
        if (txn.getZxid().compareTo(zxid) > 0) {
          iter.backward();
          break;
        }
        this.lastSeenZxid = txn.getZxid();
      }
      if (iter.hasNext()) {
        // It means there's something to truncate.
        try (RandomAccessFile ra = new RandomAccessFile(this.logFile, "rw")) {
          // Truncate the file from given position.
          ra.setLength(iter.getPosition());
        }
      }
    }
  }
625249
@Override
    public void rollLogs() {
        summaryFile = null;

        List<IncidentImpl> incidentCopies;
        synchronized (incidents) {
            incidentCopies = new ArrayList<IncidentImpl>(incidents.values());
        }

        int overage = incidentCopies.size() - 500;
        if (overage > 0) {
            // we have more than 500 incidents: we need to remove least-recently-seen
            // incidents until we're back to 500. We do this daily to prevent unchecked growth
            // in the number of incidents we remember
            List<IncidentImpl> lastSeenIncidents = new ArrayList<IncidentImpl>(incidentCopies);

            // sort the incidents by when they were last seen, rather than when they were added
            Collections.sort(lastSeenIncidents, new Comparator<IncidentImpl>() {
                @Override
                public int compare(IncidentImpl o1, IncidentImpl o2) {
                    // static method on double does the same as Long.compareTo, and we avoid
                    // object allocation or auto-boxing, etc.
                    return Double.compare(o1.getTimeStamp(), o2.getTimeStamp());
                }
            });

            // For each item we're over 500, remove one from the front of the list (least recently seen)
            synchronized (incidents) {
                for (Iterator<IncidentImpl> i = lastSeenIncidents.iterator(); i.hasNext() && overage > 0; overage--) {
                    IncidentImpl impl = i.next();
                    i.remove();

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "FFDC cleanup -- removing " + impl.key);
                    }
                    // remove the incident from the map, and clean it up (remove the associated files)
                    incidents.remove(impl.key);
                    impl.cleanup();
                }
            }
        }

        for (IncidentImpl incident : incidentCopies) {
            incident.roll();
        }

        logSummary(incidentCopies);
    }
455370
def _fast_write(self, outfile, value):
        """"""
        outfile.truncate(0)
        outfile.write(str(int(value)))
        outfile.flush()
496496
void roll() {
        m_batchLock.writeLock().lock();
        final PeriodicExportContext previous = m_current;
        try {
            m_current = new PeriodicExportContext();

            m_logger.trace("Rolling batch.");

            for( ExportToFileDecoder decoder : m_tableDecoders.values()) {
                decoder.resetWriter();
            }

        }
        finally {
            m_batchLock.writeLock().unlock();
        }
        previous.closeAllWriters();
    }
104624
def close_log(log, verbose=True):
    

    if verbose:
        print('Closing log file:', log.name)

    # Send closing message.
    log.info('The log file has been closed.')

    # Remove all handlers from log.
    [log.removeHandler(handler) for handler in log.handlers]
80560
def copy_all_lines_from_to(inputFile, outputFile):
    """"""
    currentLine = inputFile.readline()
    while currentLine:
        outputFile.write(currentLine)
        currentLine = inputFile.readline()
1295816
private void rollOverFiles() {

        Context context = appContextRef.get();

        if (context != null) {

            File dir = context.getFilesDir();

            File mainFile = new File(dir, name(1));

            if (mainFile.exists()) {

                float fileSize = mainFile.length();
                fileSize = fileSize / 1024.0f; //In kilobytes

                if (fileSize > fileSizeLimitKb) {

                    File file;
                    File target;

                    file = new File(dir, name(maxFiles));
                    if (file.exists()) {
                        file.delete();
                    }

                    for (int i = maxFiles - 1; i > 0; i--) {
                        file = new File(dir, name(i));
                        if (file.exists()) {
                            target = new File(dir, name(i + 1));
                            file.renameTo(target);
                        }
                    }
                }
            }
        }
    }
1065011
def copy_file(self, infile, outfile, check=True):
        
        self.ensure_dir(os.path.dirname(outfile))
        logger.info('Copying %s to %s', infile, outfile)
        if not self.dry_run:
            msg = None
            if check:
                if os.path.islink(outfile):
                    msg = '%s is a symlink' % outfile
                elif os.path.exists(outfile) and not os.path.isfile(outfile):
                    msg = '%s is a non-regular file' % outfile
            if msg:
                raise ValueError(msg + ' which would be overwritten')
            shutil.copyfile(infile, outfile)
        self.record_as_written(outfile)
1065913
def do_page_truncate(self, args: List[str]):
        
        if not args:
            self.perror('page_truncate requires a path to a file as an argument', traceback_war=False)
            return
        self.page_file(args[0], chop=True)
655016
def file_put_contents(self, path, data):
        

        path = self.get_full_file_path(path)

        # if file exists, create a temp copy to allow rollback
        if os.path.isfile(path):
            tmp_path = self.new_tmp()
            self.do_action({
                'do'   : ['copy', path, tmp_path],
                'undo' : ['move', tmp_path, path]})

        self.do_action(
            {'do'   : ['write', path, data],
             'undo' : ['backup', path]})
1344001
private void writePendingToFile() throws java.io.IOException, InternalLogException, LogIncompatibleException
    {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "writePendingToFile");

        synchronized (_pendingWriteList)
        {
            LogRecord[] records = (LogRecord[]) _pendingWriteList.toArray(new LogRecord[0]);

            // Don't use vectored IO unless we're told to.
            if (!Boolean.getBoolean("com.ibm.ws.recoverylog.spi.UseVectoredIO"))
            {
                // Put the file header at the front of the list
                ByteBuffer header = (ByteBuffer) _fileBuffer.duplicate().position(0).limit(_logFileHeader.length());
                _fileChannel.write(header, 0);

                // Write the remainder of the list
                for (int i = 0; i < records.length; i++)
                {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Performing write at position " + records[i].absolutePosition());
                    _fileChannel.write((ByteBuffer) records[i]._buffer.flip(), records[i].absolutePosition());
                }
            }
            else
            {
                // Sort the records into ascending order based on their absolute
                // position in the file.  We're going to try and keep the disk
                // moving forward.
                Arrays.sort(records, _recordComparator);

                // Now separate the records into two arrays:
                //   o ByteBuffers of data
                //   o Absolute File positions
                ByteBuffer[] buffers = new ByteBuffer[records.length + 1];
                int[] positions = new int[records.length + 1];

                for (int i = 0; i < records.length; i++)
                {
                    buffers[i + 1] = (ByteBuffer) records[i]._buffer.flip();
                    positions[i + 1] = records[i].absolutePosition();
                }

                // Put the file header at the front of the list
                buffers[0] = (ByteBuffer) _fileBuffer.duplicate().position(0).limit(_logFileHeader.length());
                positions[0] = 0;

                // Here's where we go through the list and attempt to write
                // batches of adjacent records using vectored I/O.
                int idx = 0;
                while (idx < buffers.length)
                {
                    int min = idx;
                    int max = idx;

                    // Somewhere in the middle
                    while (max <= (buffers.length - 2))
                    {
                        if (positions[max + 1] == (positions[max] + buffers[max].remaining()))
                            max++;
                    }

                    // Do the actual writes                    
                    _fileChannel.position(positions[min]);
                    _fileChannel.write(buffers, min, (max - min + 1));

                    // Go back and find the next batch
                    idx = max + 1;
                }
            }

            // Cleanup the pending write list for the next force
            _pendingWriteList.clear();
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "writePendingToFile");
    }
1155802
def copyfile(self, target):
        
        shutil.copyfile(self.path, self._to_backend(target))
775614
def truncate(self, size=0):
        
        if size == 0:
            self._buffer = StringIO()
            self._len_changed = True

            return

        cur_pos = self.tell()
        self.seek(0)
        buf = self.read(size)
        self._buffer = StringIO()

        self._buffer.write(buf)
        self.seek(cur_pos)
        self._len_changed = True
538661
protected function splitFiles()
    {
        $file = $this->logFile;

        for ($i = $this->maxFiles; $i >= 0; --$i) {
            // $i == 0 is the original log file
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);

            if (is_file($rotateFile)) {
                // suppress errors because it's possible multiple processes enter into this section
                if ($i === $this->maxFiles) {
                    @unlink($rotateFile);
                } else {
                    if ($this->splitByCopy) {
                        copy($rotateFile, $file . '.' . ($i + 1));
                        if ($fp = @fopen($rotateFile, 'ab')) {
                            ftruncate($fp, 0);
                            @fclose($fp);
                        }
                    } else {
                        rename($rotateFile, $file . '.' . ($i + 1));
                    }
                }
            }
        }
    }
546265
final void compress(final File backupFile,
      final AppenderRollingProperties properties) {
    if (this.isCompressed(backupFile)) {
      LogLog.debug("Backup log file " + backupFile.getName()
          + " is already compressed");
      return; // try not to do unnecessary work
    }
    final long lastModified = backupFile.lastModified();
    if (0L == lastModified) {
      LogLog.debug("Backup log file " + backupFile.getName()
          + " may have been scavenged");
      return; // backup file may have been scavenged
    }
    final File deflatedFile = this.createDeflatedFile(backupFile);
    if (deflatedFile == null) {
      LogLog.debug("Backup log file " + backupFile.getName()
          + " may have been scavenged");
      return; // an error occurred creating the file
    }
    if (this.compress(backupFile, deflatedFile, properties)) {
      deflatedFile.setLastModified(lastModified);
      FileHelper.getInstance().deleteExisting(backupFile);
      LogLog.debug("Compressed backup log file to " + deflatedFile.getName());
    } else {
      FileHelper.getInstance().deleteExisting(deflatedFile); // clean up
      LogLog
          .debug("Unable to compress backup log file " + backupFile.getName());
    }
  }
1011227
public boolean truncate(long zxid) throws IOException {
        FileTxnIterator itr = new FileTxnIterator(this.logDir, zxid);
        PositionInputStream input = itr.inputStream;
        long pos = input.getPosition();
        // now, truncate at the current position
        RandomAccessFile raf=new RandomAccessFile(itr.logFile,"rw");
        raf.setLength(pos);
        raf.close();
        while(itr.goToNextLog()) {
            if (!itr.logFile.delete()) {
                LOG.warn("Unable to truncate " + itr.logFile);
            }
        }
        return true;
    }