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


Java FileChannel.position方法代码示例

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


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

示例1: getNextTokenSize

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static long getNextTokenSize(FileChannel fileChannel, long position, byte[]... btsArr)
    throws IOException {
  long ret = -1;
  ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
  if (position >= 0) {
    fileChannel.position(position);
  }
  long startPosition = fileChannel.position();
  outer:
  while (fileChannel.read(buffer) != -1) {
    buffer.flip();
    int index;
    while ((index = findBytes(buffer, btsArr)) != -1) {
      ret = fileChannel.position() - startPosition - buffer.limit() + index;
      break outer;
    }
    buffer.clear();
  }
  fileChannel.position(startPosition);
  return ret;
}
 
开发者ID:monkeyWie,项目名称:proxyee-down,代码行数:22,代码来源:ByteUtil.java

示例2: 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

示例3: read

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Read editable Metadata
 *
 * @param file
 * @return
 * @throws CannotReadException
 * @throws IOException
 */
public AiffTag read(File file) throws CannotReadException, IOException {
    FileChannel fc = new FileOutputStream(file.getAbsolutePath(), false).getChannel();
    AiffAudioHeader aiffAudioHeader = new AiffAudioHeader();
    AiffTag aiffTag = new AiffTag();

    final AiffFileHeader fileHeader = new AiffFileHeader();
    fileHeader.readHeader(fc, aiffAudioHeader, file.toString());
    while (fc.position() < fc.size()) {
        if (!readChunk(fc, aiffTag, file.toString())) {
            logger.severe(file + " UnableToReadProcessChunk");
            break;
        }
    }

    if (aiffTag.getID3Tag() == null) {
        aiffTag.setID3Tag(AiffTag.createDefaultID3Tag());
    }
    return aiffTag;
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:28,代码来源:AiffTagReader.java

示例4: 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

示例5: copyResource

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public void copyResource(OpenForReadResult input, OutputStream outputStream) throws IOException {
    assertBackgroundThread();
    try {
        InputStream inputStream = input.inputStream;
        if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
            FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
            FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
            long offset = 0;
            long length = input.length;
            if (input.assetFd != null) {
                offset = input.assetFd.getStartOffset();
            }
            // transferFrom()'s 2nd arg is a relative position. Need to set the absolute
            // position first.
            inChannel.position(offset);
            outChannel.transferFrom(inChannel, 0, length);
        } else {
            final int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];
            
            for (;;) {
                int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
                
                if (bytesRead <= 0) {
                    break;
                }
                outputStream.write(buffer, 0, bytesRead);
            }
        }            
    } finally {
        input.inputStream.close();
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
 
开发者ID:Andy-Ta,项目名称:COB,代码行数:37,代码来源:CordovaResourceApi.java

示例6: writeMetadataSameSize

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Replace the ilst metadata
 * <p/>
 * Because it is the same size as the original data nothing else has to be modified
 *
 * @param rawIlstData
 * @param oldIlstSize
 * @param startIstWithinFile
 * @param fileReadChannel
 * @param fileWriteChannel
 * @throws CannotWriteException
 * @throws IOException
 */
private void writeMetadataSameSize(ByteBuffer rawIlstData,
                                   long oldIlstSize,
                                   long startIstWithinFile,
                                   FileChannel fileReadChannel,
                                   FileChannel fileWriteChannel,
                                   Mp4BoxHeader tagsHeader) throws CannotWriteException, IOException {
    fileReadChannel.position(0);
    fileWriteChannel.transferFrom(fileReadChannel, 0, startIstWithinFile);
    fileWriteChannel.position(startIstWithinFile);
    fileWriteChannel.write(rawIlstData);
    fileReadChannel.position(startIstWithinFile + oldIlstSize);

    writeDataAfterIlst(fileReadChannel, fileWriteChannel, tagsHeader);
}
 
开发者ID:openaudible,项目名称:openaudible,代码行数:28,代码来源:Mp4TagWriter.java

示例7: performTransfer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private void performTransfer(FileChannel source, IoCallback callback) {

        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
        try {
            long pos = source.position();
            long size = source.size();
            while (size - pos > 0) {
                int ret = source.read(buffer);
                if (ret <= 0) {
                    break;
                }
                pos += ret;
                buffer.flip();
                if (!writeBuffer(buffer, callback)) {
                    return;
                }
                buffer.clear();
            }

            if (pos != size) {
                throw new EOFException("Unexpected EOF reading file");
            }

        } catch (IOException e) {
            callback.onException(exchange, this, e);
        }
        invokeOnComplete(callback);
    }
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:BlockingWriterSenderImpl.java

示例8: getBytes

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public long getBytes(ByteBuffer readInto, long offset, int length) throws IOException {
    final long offsetInThisBucket = offsetInThisBucket(offset);
    final long lengthInThisBucket = calcLengthInThisBucket(offsetInThisBucket, length);
    final int read;
    ByteBuffer encrypted = ByteBuffer.allocate(length);
    synchronized (this) {
        final FileChannel openChannel = getOpenChannel();
        openChannel.position(offsetInThisBucket);
        read = openChannel.read(encrypted);
        if (read > 0) {
            encrypted.flip();
            encrypted.limit(read);
            final ByteBuffer decrypted = encryption.encrypt(offset, encrypted);
            readInto.put(decrypted);
        }
    }
    if (read != lengthInThisBucket) {
        final byte[] zeroes;
        if (read == -1) {
            zeroes = new byte[(int) lengthInThisBucket];
        } else {
            zeroes = new byte[(int) (lengthInThisBucket - read)];
        }
        LOGGER.debug("tried to read more bytes from this file than ever were written, replacing with {} zeroes", zeroes.length);
        readInto.put(zeroes);

    }
    return lengthInThisBucket;
}
 
开发者ID:MineboxOS,项目名称:minebox,代码行数:30,代码来源:SingleFileBucket.java

示例9: isFilePortionNull

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * @param startByte
 * @param endByte
 * @return true if all the bytes between in the file between startByte and endByte are null, false
 * otherwise
 * @throws Exception
 */
private boolean isFilePortionNull(int startByte, int endByte) throws IOException {
    logger.config("Checking file portion:" + Hex.asHex(startByte) + ":" + Hex.asHex(endByte));
    FileInputStream fis = null;
    FileChannel fc = null;
    try {
        fis = new FileInputStream(file);
        fc = fis.getChannel();
        fc.position(startByte);
        ByteBuffer bb = ByteBuffer.allocateDirect(endByte - startByte);
        fc.read(bb);
        while (bb.hasRemaining()) {
            if (bb.get() != 0) {
                return false;
            }
        }
    } finally {
        if (fc != null) {
            fc.close();
        }

        if (fis != null) {
            fis.close();
        }
    }
    return true;
}
 
开发者ID:openaudible,项目名称:openaudible,代码行数:34,代码来源:MP3File.java

示例10: nioByteBuffer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public ByteBuffer nioByteBuffer() throws IOException {
  FileChannel channel = null;
  try {
    channel = new RandomAccessFile(file, "r").getChannel();
    // Just copy the buffer if it's sufficiently small, as memory mapping has a high overhead.
    if (length < conf.memoryMapBytes()) {
      ByteBuffer buf = ByteBuffer.allocate((int) length);
      channel.position(offset);
      while (buf.remaining() != 0) {
        if (channel.read(buf) == -1) {
          throw new IOException(String.format("Reached EOF before filling buffer\n" +
            "offset=%s\nfile=%s\nbuf.remaining=%s",
            offset, file.getAbsoluteFile(), buf.remaining()));
        }
      }
      buf.flip();
      return buf;
    } else {
      return channel.map(FileChannel.MapMode.READ_ONLY, offset, length);
    }
  } catch (IOException e) {
    try {
      if (channel != null) {
        long size = channel.size();
        throw new IOException("Error in reading " + this + " (actual file length " + size + ")",
          e);
      }
    } catch (IOException ignored) {
      // ignore
    }
    throw new IOException("Error in opening " + this, e);
  } finally {
    JavaUtils.closeQuietly(channel);
  }
}
 
开发者ID:spafka,项目名称:spark_deep,代码行数:37,代码来源:FileSegmentManagedBuffer.java

示例11: run

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public boolean run(boolean complete) {
    try {
        FileChannel source = fileChannel;
        long pos = source.position();
        long size = source.size();

        StreamSinkChannel dest = channel;
        if (dest == null) {
            if (callback == IoCallback.END_EXCHANGE) {
                if (exchange.getResponseContentLength() == -1 && !exchange.getResponseHeaders().contains(Headers.TRANSFER_ENCODING)) {
                    exchange.setResponseContentLength(size);
                }
            }
            channel = dest = exchange.getResponseChannel();
            if (dest == null) {
                throw UndertowMessages.MESSAGES.responseChannelAlreadyProvided();
            }
        }

        while (size - pos > 0) {
            long ret = dest.transferFrom(source, pos, size - pos);
            pos += ret;
            if (ret == 0) {
                source.position(pos);
                dest.getWriteSetter().set(this);
                dest.resumeWrites();
                return false;
            }
        }

        if (complete) {
            invokeOnComplete();
        }
    } catch (IOException e) {
        invokeOnException(callback, e);
    }

    return true;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:40,代码来源:AsyncSenderImpl.java

示例12: ID3v11Tag

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Creates a new ID3v11 datatype.
 *
 * @param file
 * @param loggingFilename
 * @throws TagNotFoundException
 * @throws IOException
 */
public ID3v11Tag(RandomAccessFile file, String loggingFilename) throws TagNotFoundException, IOException
{
    setLoggingFilename(loggingFilename);
    FileChannel fc;
    ByteBuffer byteBuffer = ByteBuffer.allocate(TAG_LENGTH);

    fc = file.getChannel();
    fc.position(file.length() - TAG_LENGTH);

    fc.read(byteBuffer);
    byteBuffer.flip();
    read(byteBuffer);

}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:23,代码来源:ID3v11Tag.java

示例13: delete

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Delete tag from file
 * Looks for tag and if found lops it off the file.
 *
 * @param file to delete the tag from
 * @throws IOException if there was a problem accessing the file
 */
public void delete(RandomAccessFile file) throws IOException
{
    //Read into Byte Buffer
    logger.config("Deleting ID3v1 from file if exists");

    FileChannel fc;
    ByteBuffer byteBuffer;
    fc = file.getChannel();

    if(file.length() < TAG_LENGTH)
    {
        throw new IOException("File not not appear large enough to contain a tag");
    }
    fc.position(file.length() - TAG_LENGTH);
    byteBuffer = ByteBuffer.allocate(TAG_LENGTH);
    fc.read(byteBuffer);
    byteBuffer.rewind();
    if (AbstractID3v1Tag.seekForV1OrV11Tag(byteBuffer))
    {
        try
        {
            logger.config("Deleted ID3v1 tag");
            file.setLength(file.length() - TAG_LENGTH);
        }
        catch(IOException ex)
        {
            logger.severe("Unable to delete existing ID3v1 Tag:"+ex.getMessage());
        }
    }
    else
    {
        logger.config("Unable to find ID3v1 tag to deleteField");
    }
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:42,代码来源:AbstractID3v1Tag.java

示例14: writeNeroData

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * If the existing files contains a tags atom and chp1 atom underneath the meta atom that means the file was
 * encoded by Nero. Applications such as foobar read this non-standard tag before the more usual data within
 * {@code ilst} causing problems. So the solution is to convert the tags atom and its children into a free atom whilst
 * leaving the chp1 atom alone.
 *
 * @param fileReadChannel
 * @param fileWriteChannel
 * @param tagsHeader
 * @throws IOException
 */
private void writeNeroData(FileChannel fileReadChannel, FileChannel fileWriteChannel, Mp4BoxHeader tagsHeader) throws IOException, CannotWriteException
{
    //Write from after ilst upto tags atom
    long writeBetweenIlstAndTags = tagsHeader.getFilePos() - fileReadChannel.position();
    fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), writeBetweenIlstAndTags);
    fileWriteChannel.position(fileWriteChannel.position() + writeBetweenIlstAndTags);

    //Replace tags atom (and children) by a free atom
    convertandWriteTagsAtomToFreeAtom(fileWriteChannel, tagsHeader);

    //Write after tags atom
    fileReadChannel.position(tagsHeader.getFileEndPos());
    writeDataInChunks(fileReadChannel, fileWriteChannel);
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:26,代码来源:Mp4TagWriter.java

示例15: read

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public void
read(
	RandomAccessFile	raf,
	DirectByteBuffer	buffer,
	long				offset )

	throws FMFileManagerException
{
	if (raf == null){

		throw new FMFileManagerException( "read: raf is null" );
	}

	FileChannel fc = raf.getChannel();

	if ( !fc.isOpen()){

		Debug.out("FileChannel is closed: " + owner.getName());

		throw( new FMFileManagerException( "read - file is closed"));
	}

	AEThread2.setDebug( owner );

	try{
		if(USE_MMAP)
		{
			long remainingInFile = fc.size()-offset;
			long remainingInTargetBuffer = buffer.remaining(DirectByteBuffer.SS_FILE);
			MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, offset, Math.min(remainingInFile,remainingInTargetBuffer));
			buffer.put(DirectByteBuffer.SS_FILE, buf);
		} else {
			fc.position(offset);
			while (fc.position() < fc.size() && buffer.hasRemaining(DirectByteBuffer.SS_FILE))
				buffer.read(DirectByteBuffer.SS_FILE,fc);
		}



	}catch ( Exception e ){

		Debug.printStackTrace( e );

		throw( new FMFileManagerException( "read fails", e ));
	}
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:47,代码来源:FMFileAccessLinear.java


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