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


Java FileChannel.size方法代码示例

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


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

示例1: nioCopy

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Copy a single file using NIO.
 * @throws IOException
 */
private static void nioCopy(FileOutputStream fos, FileInputStream fis)
    throws IOException {
  FileChannel outChannel = fos.getChannel();
  FileChannel inChannel = fis.getChannel();
  long length = inChannel.size();
  long offset = 0;
  while(true) {
    long remaining = length - offset;

    long toTransfer = remaining < MAX_TRANSFER_SIZE ? remaining : MAX_TRANSFER_SIZE;
    long transferredBytes = inChannel.transferTo(offset, toTransfer, outChannel);
    offset += transferredBytes;
    length = inChannel.size();
    if(offset >= length) {
      break;
    }
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:23,代码来源:FileUtil.java

示例2: writeDataInChunks

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * #385 Write data in chunks, needed if writing large amounts of data
 *
 * @param fileReadChannel
 * @param fileWriteChannel
 * @throws IOException
 * @throws CannotWriteException
 */
private void writeDataInChunks(FileChannel fileReadChannel, FileChannel fileWriteChannel)
        throws IOException, CannotWriteException {
    long amountToBeWritten = fileReadChannel.size() - fileReadChannel.position();
    long written = 0;
    long chunksize = TagOptionSingleton.getInstance().getWriteChunkSize();
    long count = amountToBeWritten / chunksize;

    long mod = amountToBeWritten % chunksize;
    for (int i = 0; i < count; i++) {
        written += fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), chunksize);
        fileWriteChannel.position(fileWriteChannel.position() + chunksize);
    }
    written += fileWriteChannel.transferFrom(fileReadChannel, fileWriteChannel.position(), mod);
    if (written != amountToBeWritten) {
        throw new CannotWriteException("Was meant to write " + amountToBeWritten + " bytes but only written " + written + " bytes");
    }
}
 
开发者ID:openaudible,项目名称:openaudible,代码行数:26,代码来源:Mp4TagWriter.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: readFile2BytesByMap

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 读取文件到字符数组中
 *
 * @param file 文件
 * @return 字符数组
 */
public static byte[] readFile2BytesByMap(File file) {
    if (file == null) return null;
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "r").getChannel();
        MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load();
        byte[] result = new byte[(int) fc.size()];
        if (byteBuffer.remaining() > 0) {
            byteBuffer.get(result, 0, byteBuffer.remaining());
        }
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:penghongru,项目名称:Coder,代码行数:25,代码来源:FileUtils.java

示例5: readFileWithFileSizeBuffer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static StrBuilder readFileWithFileSizeBuffer(Path file ) throws IOException
{
    FileChannel inChannel = null;
    RandomAccessFile aFile = null;
    StrBuilder builder = new StrBuilder();
    try
    {
        aFile = new RandomAccessFile( file.toString(), "r" );
        inChannel = aFile.getChannel();
        long fileSize = inChannel.size();
        ByteBuffer buffer = ByteBuffer.allocate( ( int ) fileSize );
        inChannel.read( buffer );
        buffer.flip();
        for ( int i = 0; i < fileSize; i++ )
        {
            builder.append( ( char ) buffer.get() );
        }

        return builder.trim();
    }
    finally
    {
        if( null != inChannel ) inChannel.close();
        if( null != aFile ) aFile.close();
    }
}
 
开发者ID:hemano,项目名称:cucumber-framework-java,代码行数:27,代码来源:FileUtils.java

示例6: readFile2BytesByMap

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * 读取文件到字节数组中
 *
 * @param file 文件
 * @return 字符数组
 */
public static byte[] readFile2BytesByMap(File file) {
    if (!FileUtils.isFileExists(file)) return null;
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "r").getChannel();
        int size = (int) fc.size();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
        byte[] result = new byte[size];
        mbb.get(result, 0, size);
        return result;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
 
开发者ID:pan2yong22,项目名称:AndroidUtilCode-master,代码行数:24,代码来源:FileIOUtils.java

示例7: copyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public static void copyFile(File sourceFile, File destFile) throws IOException {
	if (!destFile.exists()) {
		destFile.createNewFile();
	}

	FileChannel source = null;
	FileChannel destination = null;
	try {
		source = new FileInputStream(sourceFile).getChannel();
		destination = new FileOutputStream(destFile).getChannel();

		//previous code: destination.transferFrom(source, 0, source.size());
		//should be to avoid infinite loops.

		long count = 0;
		long size = source.size();                
		while ((count += destination.transferFrom(source, 0, size - count)) < size);
	} finally {
		if (source != null) {
			source.close();
		}
		if (destination != null) {
			destination.close();
		}
	}
}
 
开发者ID:max6cn,项目名称:jmt,代码行数:27,代码来源:Jmt.java

示例8: create

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
static ReadBuffer create(RandomAccessFile file) throws IOException {
    FileChannel ch = file.getChannel();
    long size = ch.size();
    // if file size is more than 2 GB and when file mapping is
    // configured (default), use mapped file reader
    if (canUseFileMap() && (size <= Integer.MAX_VALUE)) {
        MappedByteBuffer buf;
        try {
            buf = ch.map(FileChannel.MapMode.READ_ONLY, 0, size);
            ch.close();
            return new MappedReadBuffer(buf);
        } catch (IOException exp) {
            exp.printStackTrace();
            System.err.println("File mapping failed, will use direct read");
            // fall through
        }
    } // else fall through
    return new FileReadBuffer(file);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:20,代码来源:MappedReadBuffer.java

示例9: read

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public int read(String name, ByteBuffer dst) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), true, false);

    // wrap with channel
    FileChannel fc = null;
    try {
        Set<OpenOption> opts = new HashSet<>();
        opts.add(READ);
        if (!followLinks)
            opts.add(WindowsChannelFactory.OPEN_REPARSE_POINT);
        fc = WindowsChannelFactory
            .newFileChannel(join(file, name), null, opts, 0L);
    } catch (WindowsException x) {
        x.rethrowAsIOException(join(file.getPathForPermissionCheck(), name));
    }

    // read to EOF (nothing we can do if I/O error occurs)
    try {
        if (fc.size() > dst.remaining())
            throw new IOException("Stream too large");
        int total = 0;
        while (dst.hasRemaining()) {
            int n = fc.read(dst);
            if (n < 0)
                break;
            total += n;
        }
        return total;
    } finally {
        fc.close();
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:35,代码来源:WindowsUserDefinedFileAttributeView.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: parseBreakNumByCheck

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private int parseBreakNumByCheck(Task task) {
    String taskId = task.getTaskId();
    Integer pieceSize = task.getPieceSize();
    long position = 0;
    ByteBuffer bb = generateByteBuffer();
    try (FileInputStream fis = new FileInputStream(PathUtil.getDownloadPathStr(taskId))) {
        FileChannel fc = fis.getChannel();
        long curFileLen = (fc.size() / pieceSize - 1) * pieceSize;
        curFileLen = curFileLen > 0 ? curFileLen : 0;
        int pieceLen;
        while (position < curFileLen) {
            bb.clear();
            bb.limit(4);
            fc.read(bb, position);
            bb.flip();
            pieceLen = bb.getInt() & 0xffffff;
            if (pieceLen > 0) {
                bb.clear();
                bb.limit(1);
                fc.read(bb, pieceLen + position + 4);
                bb.flip();
                if (bb.get() == (byte)0x7f) {
                    position += pieceSize;
                    continue;
                }
            }
            break;
        }
    } catch (Exception e) {
        logger.error("parse break num by check error for taskId:{}", taskId, e);
    }
    return (int)(position / pieceSize);
}
 
开发者ID:alibaba,项目名称:Dragonfly,代码行数:34,代码来源:CacheDetectorImpl.java

示例12: HprofMappedByteBuffer

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
HprofMappedByteBuffer(File dumpFile) throws IOException {
    FileInputStream fis = new FileInputStream(dumpFile);
    FileChannel channel = fis.getChannel();
    length = channel.size();
    dumpBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
    channel.close();
    readHeader();
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:9,代码来源:HprofMappedByteBuffer.java

示例13: doCopyFile

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Internal copy file method.
 *
 * @param srcFile          the validated source file, must not be {@code null}
 * @param destFile         the validated destination file, must not be {@code null}
 * @param preserveFileDate whether to preserve the file date
 * @throws java.io.IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" +
                srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}
 
开发者ID:jqjm,项目名称:Liteframework,代码行数:45,代码来源:FileUtils.java

示例14: transferToFully

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Transfers data from FileChannel using 
 * {@link FileChannel#transferTo(long, long, WritableByteChannel)}. 
 * 
 * Similar to readFully(), this waits till requested amount of 
 * data is transfered.
 * 
 * @param fileCh FileChannel to transfer data from.
 * @param position position within the channel where the transfer begins
 * @param count number of bytes to transfer.
 * 
 * @throws EOFException 
 *         If end of input file is reached before requested number of 
 *         bytes are transfered.
 *
 * @throws SocketTimeoutException 
 *         If this channel blocks transfer longer than timeout for 
 *         this stream.
 *          
 * @throws IOException Includes any exception thrown by 
 *         {@link FileChannel#transferTo(long, long, WritableByteChannel)}. 
 */
public void transferToFully(FileChannel fileCh, long position, int count) 
                            throws IOException {
  
  while (count > 0) {
    /* 
     * Ideally we should wait after transferTo returns 0. But because of
     * a bug in JRE on Linux (http://bugs.sun.com/view_bug.do?bug_id=5103988),
     * which throws an exception instead of returning 0, we wait for the
     * channel to be writable before writing to it. If you ever see 
     * IOException with message "Resource temporarily unavailable" 
     * thrown here, please let us know.
     * 
     * Once we move to JAVA SE 7, wait should be moved to correct place.
     */
    waitForWritable();
    int nTransfered = (int) fileCh.transferTo(position, count, getChannel());
    
    if (nTransfered == 0) {
      //check if end of file is reached.
      if (position >= fileCh.size()) {
        throw new EOFException("EOF Reached. file size is " + fileCh.size() + 
                               " and " + count + " more bytes left to be " +
                               "transfered.");
      }
      //otherwise assume the socket is full.
      //waitForWritable(); // see comment above.
    } else if (nTransfered < 0) {
      throw new IOException("Unexpected return of " + nTransfered + 
                            " from transferTo()");
    } else {
      position += nTransfered;
      count -= nTransfered;
    }
  }
}
 
开发者ID:spafka,项目名称:spark_deep,代码行数:58,代码来源:SocketOutputStream.java

示例15: loadBaseAndCheckByFileChannel

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private boolean loadBaseAndCheckByFileChannel(String path)
{
    try
    {
        FileInputStream fis = new FileInputStream(path);
        // 1.从FileInputStream对象获取文件通道FileChannel
        FileChannel channel = fis.getChannel();
        int fileSize = (int) channel.size();

        // 2.从通道读取文件内容
        ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);

        // channel.read(ByteBuffer) 方法就类似于 inputstream.read(byte)
        // 每次read都将读取 allocate 个字节到ByteBuffer
        channel.read(byteBuffer);
        // 注意先调用flip方法反转Buffer,再从Buffer读取数据
        byteBuffer.flip();
        // 有几种方式可以操作ByteBuffer
        // 可以将当前Buffer包含的字节数组全部读取出来
        byte[] bytes = byteBuffer.array();
        byteBuffer.clear();
        // 关闭通道和文件流
        channel.close();
        fis.close();

        int index = 0;
        size = ByteUtil.bytesHighFirstToInt(bytes, index);
        index += 4;
        base = new int[size + 65535];   // 多留一些,防止越界
        check = new int[size + 65535];
        for (int i = 0; i < size; i++)
        {
            base[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
            index += 4;
            check[i] = ByteUtil.bytesHighFirstToInt(bytes, index);
            index += 4;
        }
    }
    catch (Exception e)
    {
        return false;
    }
    return true;
}
 
开发者ID:priester,项目名称:hanlpStudy,代码行数:45,代码来源:DoubleArrayTrie.java


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