当前位置: 首页>>代码示例>>Java>>正文


Java FileChannel.truncate方法代码示例

本文整理汇总了Java中java.nio.channels.FileChannel.truncate方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.truncate方法的具体用法?Java FileChannel.truncate怎么用?Java FileChannel.truncate使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.FileChannel的用法示例。


在下文中一共展示了FileChannel.truncate方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: storeSession

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public void storeSession(@NonNull SignalProtocolAddress address, @NonNull SessionRecord record) {
  synchronized (FILE_LOCK) {
    try {
      RandomAccessFile sessionFile  = new RandomAccessFile(getSessionFile(address), "rw");
      FileChannel      out          = sessionFile.getChannel();

      out.position(0);
      writeInteger(CURRENT_VERSION, out);
      writeBlob(record.serialize(), out);
      out.truncate(out.position());

      sessionFile.close();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }
}
 
开发者ID:XecureIT,项目名称:PeSanKita-android,代码行数:19,代码来源:TextSecureSessionStore.java

示例2: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Copy file
 *
 * @param sourceFileName the source file name
 * @param destinationFileName the destination file name
 * @throws IOException on error
 */
private void copyFile( String sourceFileName, String destinationFileName ) throws IOException {

    FileChannel srcChannel = null;
    FileChannel dstChannel = null;

    try {
        // Create channel on the source
        srcChannel = new FileInputStream(sourceFileName).getChannel();

        // Create channel on the destination
        dstChannel = new FileOutputStream(destinationFileName).getChannel();

        // Copy file contents from source to destination
        dstChannel.truncate(0);
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
    } finally {
        // Close the channels
        IoUtils.closeStream(srcChannel);
        IoUtils.closeStream(dstChannel);
    }
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:29,代码来源:FileEnvironmentUnit.java

示例3: truncateFileAtURL

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
开发者ID:alex-shpak,项目名称:keemob,代码行数:24,代码来源:LocalFilesystem.java

示例4: NanoLogger

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Instantiates a new <code>NanoLogger</code> object and creates the logfile at <code>filepath</code>
 * @param filepath the path to save the log at
 * @param truncate whether or not to truncate the file if it already exists
 */
public NanoLogger(String filepath, boolean truncate){
    logfile = new File(filepath);

    try {
        if (!logfile.exists()){
            logfile.createNewFile();
        } else {
            // Truncate file to 0
            FileChannel out = new FileOutputStream(logfile, true).getChannel();
            out.truncate(0);
            out.close();
        }
        fw = new FileWriter(logfile);
        out = new BufferedWriter(fw);
    } catch (IOException ioe){
        ioe.printStackTrace();
    }
}
 
开发者ID:cbrnrd,项目名称:NanoLog,代码行数:24,代码来源:NanoLogger.java

示例5: delete

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Delete given {@link Tag} from file.
 *
 * @param tag  tag, must be instance of {@link AiffTag}
 * @param file
 * @throws java.io.IOException
 * @throws org.jaudiotagger.audio.exceptions.CannotWriteException
 */
public void delete(final Tag tag, File file) throws CannotWriteException {
    try {
        FileChannel fc = new FileOutputStream(file.getAbsolutePath(), false).getChannel();
        logger.severe(file.getAbsolutePath() + " Deleting tag from file");
        final AiffTag existingTag = getExistingMetadata(file);

        if (existingTag.isExistingId3Tag() && existingTag.getID3Tag().getStartLocationInFile() != null) {
            ChunkHeader chunkHeader = seekToStartOfMetadata(fc, existingTag, file.getAbsolutePath());
            if (isAtEndOfFileAllowingForPaddingByte(existingTag, fc)) {
                logger.severe(file.getAbsolutePath() + " Setting new length to:" + (existingTag.getStartLocationInFileOfId3Chunk()));
                fc.truncate(existingTag.getStartLocationInFileOfId3Chunk());
            } else {
                logger.severe(file.getAbsolutePath() + " Deleting tag chunk");
                deleteTagChunk(fc, existingTag, chunkHeader, file.getAbsolutePath());
            }
            rewriteRiffHeaderSize(fc);
        }
        logger.severe(file.getAbsolutePath() + " Deleted tag from file");
    } catch (IOException ioe) {
        throw new CannotWriteException(file.getAbsolutePath() + ":" + ioe.getMessage());
    }
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:31,代码来源:AiffTagWriter.java

示例6: deleteTagChunk

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * <p>Deletes the given ID3-{@link Tag}/{@link Chunk} from the file by moving all following chunks up.</p>
 * <pre>
 * [chunk][-id3-][chunk][chunk]
 * [chunk] &lt;&lt;--- [chunk][chunk]
 * [chunk][chunk][chunk]
 * </pre>
 *
 * @param fc,            filechannel
 * @param existingTag    existing tag
 * @param tagChunkHeader existing chunk header for the tag
 * @throws IOException if something goes wrong
 */
private void deleteTagChunk(FileChannel fc, final AiffTag existingTag, final ChunkHeader tagChunkHeader, String fileName) throws IOException {
    int lengthTagChunk = (int) tagChunkHeader.getSize() + ChunkHeader.CHUNK_HEADER_SIZE;
    if (Utils.isOddLength(lengthTagChunk)) {
        if (existingTag.getStartLocationInFileOfId3Chunk() + lengthTagChunk < fc.size()) {
            lengthTagChunk++;
        }
    }
    final long newLength = fc.size() - lengthTagChunk;
    logger.severe(fileName + " Size of id3 chunk to delete is:" + lengthTagChunk + ":Location:" + existingTag.getStartLocationInFileOfId3Chunk());

    // position for reading after the id3 tag
    fc.position(existingTag.getStartLocationInFileOfId3Chunk() + lengthTagChunk);

    deleteTagChunkUsingSmallByteBufferSegments(existingTag, fc, newLength, lengthTagChunk);
    // truncate the file after the last chunk
    logger.severe(fileName + " Setting new length to:" + newLength);
    fc.truncate(newLength);
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:32,代码来源:AiffTagWriter.java

示例7: insertContent

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void insertContent(String path, long offset, byte[] content) throws IOException {
  RandomAccessFile sourceRaf = new RandomAccessFile(path, "rw");
  File tempFile = FileUtil.createFile(path + ".tmp");
  RandomAccessFile tempRaf = new RandomAccessFile(tempFile, "rw");
  long fileSize = sourceRaf.length();
  FileChannel sourceChannel = sourceRaf.getChannel();
  FileChannel targetChannel = tempRaf.getChannel();
  long remaining = fileSize - offset;
  long position = offset;
  while (remaining > 0) {
    long transferred = sourceChannel.transferTo(position, remaining, targetChannel);
    remaining -= transferred;
    position += transferred;
  }
  sourceChannel.truncate(offset);
  sourceRaf.seek(offset);
  sourceRaf.write(content);
  long newOffset = sourceRaf.getFilePointer();
  targetChannel.position(0);
  sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
  sourceChannel.close();
  targetChannel.close();
  FileUtil.deleteIfExists(tempFile);
}
 
开发者ID:monkeyWie,项目名称:proxyee-down,代码行数:25,代码来源:ByteUtil.java

示例8: deleteTagChunk

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Delete Tag Chunk
 * <p/>
 * Can be used when chunk is not the last chunk
 * <p/>
 * Continually copy a 4mb chunk, write the chunk and repeat until the rest of the file after the tag
 * is rewritten
 *
 * @param fc
 * @param endOfExistingChunk
 * @param lengthTagChunk
 * @throws IOException
 */
private void deleteTagChunk(final FileChannel fc, int endOfExistingChunk, final int lengthTagChunk) throws IOException {
    //Position for reading after the tag
    fc.position(endOfExistingChunk);

    final ByteBuffer buffer = ByteBuffer.allocate((int) TagOptionSingleton.getInstance().getWriteChunkSize());
    while (fc.read(buffer) >= 0 || buffer.position() != 0) {
        buffer.flip();
        final long readPosition = fc.position();
        fc.position(readPosition - lengthTagChunk - buffer.limit());
        fc.write(buffer);
        fc.position(readPosition);
        buffer.compact();
    }
    //Truncate the file after the last chunk
    final long newLength = fc.size() - lengthTagChunk;
    logger.config(loggingName + " Setting new length to:" + newLength);
    fc.truncate(newLength);
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:32,代码来源:WavTagWriter.java

示例9: trim

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public void trim(long offset, long length) throws IOException {
    final long offsetInThisBucket = offsetInThisBucket(offset);
    final long lengthInThisBucket = calcLengthInThisBucket(offsetInThisBucket, length); //should be always equal to length since it is normalized in MineboxEport
    final FileChannel channel = getOpenChannel();
    final long fileSize = channel.size();
    if (fileSize == 0 || offsetInThisBucket >= fileSize) {
        //if the file is empty, there is nothing to trim
    } else if (lengthInThisBucket == this.bucketSize) {
        if (fileSize > 0)
        //if we are trimming the whole bucket we can truncate to 0
        {
            synchronized (this) {
                channel.truncate(0);
                channel.force(true);
            }
            needsFlush = true;
        }
    } else if (offsetInThisBucket == 0 && lengthInThisBucket >= fileSize) {
        //we are trimming the whole file, so we can truncate it.
        synchronized (this) {
            channel.truncate(0);
            channel.force(true);
        }
        needsFlush = true;
    } else if (offsetInThisBucket + lengthInThisBucket == this.bucketSize) {
        //truncating from index until end, we can shorten the file now
        synchronized (this) {
            channel.truncate(offsetInThisBucket);
            channel.force(false); //since we assume the un-truncated file was actually backed up, we don't care if this shortened file is not the one uploaded, since truncate is a "best effort" operations btrfs should tolerate those data being non-zero
        }
        needsFlush = true;
    } else {
        final int intLen = Ints.checkedCast(length); //buckets can not be bigger than 2GB right now, could be fixed
        final ByteBuffer bb = ByteBuffer.allocate(intLen);
        bb.put(new byte[intLen]);
        bb.flip();
        putBytesInternal(offset, bb, false); //sadly, this will encrypt zeroes. we need a workaround
    }
}
 
开发者ID:MineboxOS,项目名称:minebox,代码行数:41,代码来源:SingleFileBucket.java

示例10: xferTest03

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Test
public void xferTest03() throws Exception { // for bug 4559072
    byte[] srcData = new byte[] {1,2,3,4} ;

    // get filechannel for the source file.
    File source = File.createTempFile("source", null);
    source.deleteOnExit();
    RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
    FileChannel fc1 = raf1.getChannel();
    fc1.truncate(0);

    // write out data to the file channel
    int bytesWritten = 0;
    while (bytesWritten < 4) {
        bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
    }

    // get filechannel for the dst file.
    File dest = File.createTempFile("dest", null);
    dest.deleteOnExit();
    RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
    FileChannel fc2 = raf2.getChannel();
    fc2.truncate(0);

    fc1.transferTo(0, srcData.length + 1, fc2);

    if (fc2.size() > 4)
        throw new Exception("xferTest03 failed");

    fc1.close();
    fc2.close();
    raf1.close();
    raf2.close();

    source.delete();
    dest.delete();
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:38,代码来源:Transfer.java

示例11: storeSerializedRecord

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void storeSerializedRecord(File file, byte[] serialized) throws IOException {
  RandomAccessFile recordFile = new RandomAccessFile(file, "rw");
  FileChannel      out        = recordFile.getChannel();

  out.position(0);
  writeInteger(CURRENT_VERSION_MARKER, out);
  writeBlob(serialized, out);
  out.truncate(out.position());
  recordFile.close();
}
 
开发者ID:XecureIT,项目名称:PeSanKita-android,代码行数:11,代码来源:TextSecurePreKeyStore.java

示例12: writeStatusToFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void writeStatusToFile(FileChannel channel) throws IOException
{
    long size = getBufferSize();

    ByteBuffer buffer;
    if (useNIOMemoryMapping)
    {
        MappedByteBuffer mbb = channel.map(MapMode.READ_WRITE, 0, size);
        mbb.load();
        buffer = mbb;
    }
    else
    {
        channel.truncate(size);
        buffer = ByteBuffer.wrap(new byte[(int) size]);
    }

    buffer.position(0);

    buffer.putLong(version);
    CRC32 crc32 = new CRC32();
    crc32.update((int) (version >>> 32) & 0xFFFFFFFF);
    crc32.update((int) (version >>> 0) & 0xFFFFFFFF);

    buffer.putInt(indexEntries.size());
    crc32.update(indexEntries.size());

    for (IndexEntry entry : indexEntries.values())
    {
        String entryType = entry.getType().toString();
        writeString(buffer, crc32, entryType);

        writeString(buffer, crc32, entry.getName());

        writeString(buffer, crc32, entry.getParentName());

        String entryStatus = entry.getStatus().toString();
        writeString(buffer, crc32, entryStatus);

        writeString(buffer, crc32, entry.getMergeId());

        buffer.putLong(entry.getDocumentCount());
        crc32.update((int) (entry.getDocumentCount() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDocumentCount() >>> 0) & 0xFFFFFFFF);

        buffer.putLong(entry.getDeletions());
        crc32.update((int) (entry.getDeletions() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDeletions() >>> 0) & 0xFFFFFFFF);

        buffer.put(entry.isDeletOnlyNodes() ? (byte) 1 : (byte) 0);
        crc32.update(entry.isDeletOnlyNodes() ? new byte[] { (byte) 1 } : new byte[] { (byte) 0 });
    }
    buffer.putLong(crc32.getValue());

    if (useNIOMemoryMapping)
    {
        ((MappedByteBuffer) buffer).force();
    }
    else
    {
        buffer.rewind();
        channel.position(0);
        channel.write(buffer);
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:66,代码来源:IndexInfo.java

示例13: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@SuppressWarnings( "resource")
@Override
public void copyFile(
                      String sourceFile,
                      String destinationFile,
                      boolean failOnError ) {

    File inputFile = new File(sourceFile);
    checkFileExistence(inputFile);

    FileChannel srcChannel = null;
    FileChannel dstChannel = null;

    try {
        // Create channel on the source
        srcChannel = new FileInputStream(sourceFile).getChannel();

        // Create channel on the destination
        dstChannel = new FileOutputStream(destinationFile).getChannel();

        // Copy file contents from source to destination
        dstChannel.truncate(0);

        if (log.isDebugEnabled()) {
            log.debug("Copying file '" + sourceFile + "' of " + srcChannel.size() + "bytes to '"
                      + destinationFile + "'");
        }

        /* Copy the file in chunks.
         * If we provide the whole file at once, the copy process does not start or does not
         * copy the whole file on some systems when the file is a very large one - usually
         * bigger then 2 GBs
         */
        final long CHUNK = 16 * 1024 * 1024; // 16 MB chunks
        for (long pos = 0; pos < srcChannel.size();) {
            pos += dstChannel.transferFrom(srcChannel, pos, CHUNK);
        }

        if (srcChannel.size() != dstChannel.size()) {
            throw new FileSystemOperationException("Size of the destination file \"" + destinationFile
                                                   + "\" and the source file \"" + sourceFile
                                                   + "\" missmatch!");
        }

        if (osType.isUnix()) {
            // set the original file permission to the new file
            setFilePermissions(destinationFile, getFilePermissions(sourceFile));
        }

    } catch (IOException e) {
        throw new FileSystemOperationException("Unable to copy file '" + sourceFile + "' to '"
                                               + destinationFile + "'", e);
    } finally {
        // Close the channels
        IoUtils.closeStream(srcChannel,
                            "Unable to close input channel while copying file '" + sourceFile + "' to '"
                                        + destinationFile + "'");
        IoUtils.closeStream(dstChannel,
                            "Unable to close destination channel while copying file '" + sourceFile
                                        + "' to '" + destinationFile + "'");
    }
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:63,代码来源:LocalFileSystemOperations.java


注:本文中的java.nio.channels.FileChannel.truncate方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。