Java 类java.nio.MappedByteBuffer 实例源码

项目:GitHub    文件:FileIOUtils.java   
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByMap(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
    if (bytes == null || !createOrExistsFile(file)) return false;
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
        mbb.put(bytes);
        if (isForce) mbb.force();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:proxyee-down    文件:LargeMappedByteBuffer.java   
public final void put(ByteBuffer byteBuffer) throws IOException {
  try {
    int index = getIndex();
    long length = byteBuffer.limit() - byteBuffer.position();
    this.position += length;
    MappedByteBuffer mappedBuffer = bufferList.get(index);
    if (mappedBuffer.remaining() < length) {
      byte[] temp = new byte[mappedBuffer.remaining()];
      byteBuffer.get(temp);
      bufferList.get(index).put(temp);
      bufferList.get(index + 1).put(byteBuffer);
    } else {
      bufferList.get(index).put(byteBuffer);
    }
  } catch (Exception e) {
    throw new IOException("LargeMappedByteBuffer put rawPosition-"+rawPosition+" size-"+size, e);
  }
}
项目:dataset-lib    文件:StreamThread.java   
public ByteBuffer call() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    buff = ByteBuffer.allocate(bufferSize);
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    while (!stop.isLocked()) {
        RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.read(buff);
        FileChannel channel = temp.getChannel();
        channel.write(buff);
        if (!pause.isLocked()) {
            MappedByteBuffer b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
            b.clear();
        }
        temp.close();
        buff.clear();
    }

    return null;
}
项目:dataset-lib    文件:StreamThread.java   
public ByteBuffer call() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    buff = ByteBuffer.allocate(bufferSize);
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
    MappedByteBuffer b;
    while (!stop.isLocked()) {
        sync=0;
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.read(buff);
        FileChannel channel = temp.getChannel();
        channel.write(buff);
        if (!pause.isLocked()) {
            b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
            sync = 1;
            if(sync==2){
            b.clear();
            }
        }
        buff.clear();
    }
    temp.close();
    return null;
}
项目:HeadlineNews    文件:FileIOUtils.java   
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByMap(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
    if (bytes == null || !createOrExistsFile(file)) return false;
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
        mbb.put(bytes);
        if (isForce) mbb.force();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:incubator-netbeans    文件:OpenFormTest.java   
private void copy(File source, File destination) throws IOException {
    FileChannel input = null, output = null;
    try {
        input = new FileInputStream(source).getChannel();
        output = new FileOutputStream(destination).getChannel();

        long size = input.size();
        MappedByteBuffer buffer = input.map(FileChannel.MapMode.READ_ONLY, 0, size);

        output.write(buffer);

    } finally {
        if (input != null)
            input.close();
        if (output != null)
            output.close();
    }
}
项目:Android-UtilCode    文件:FileIOUtils.java   
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByMap(File file, final byte[] bytes, boolean append, boolean isForce) {
    if (bytes == null || !FileUtils.createOrExistsFile(file)) return false;
    if (!append && !FileUtils.createFileByDeleteOldFile(file)) return false;
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "rw").getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
        mbb.put(bytes);
        if (isForce) mbb.force();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:HeadlineNews    文件:CacheUtils.java   
private static byte[] readFile2Bytes(final File file) {
    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[] data = new byte[size];
        mbb.get(data, 0, size);
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:Android-UtilCode    文件:CacheUtils.java   
/**
 * 缓存中读取字节数组
 *
 * @param key 键
 * @return 字节数组
 */
public byte[] getBytes(String key) {
    File file = mCacheManager.getFile(key);
    if (!file.exists()) return null;
    FileChannel fc = null;
    try {
        fc = new RandomAccessFile(file, "r").getChannel();
        int size = (int) fc.size();
        MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
        byte[] data = new byte[size];
        byteBuffer.get(data, 0, size);
        if (!CacheHelper.isDue(data)) {
            return CacheHelper.getDataWithoutDueTime(data);
        } else {
            mCacheManager.remove(key);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        CloseUtils.closeIO(fc);
    }
    return null;
}
项目:LuaViewPlayground    文件:ChannelTools.java   
/**
 * file path to
 *
 * @param filepath
 * @param sizes
 * @return
 */
public static List<byte[]> toBytes(String filepath, int[] sizes) {
    List<byte[]> result = new ArrayList<byte[]>();
    try {
        RandomAccessFile randomAccessFile = new RandomAccessFile(filepath, "r");
        MappedByteBuffer buffer = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());

        if (sizes != null && sizes.length > 0) {
            for (int size : sizes) {
                byte[] r = new byte[size];
                buffer.get(r);//fill buffer
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
项目:Gospy    文件:FileMappedQueue.java   
public void load() throws IOException {
    logger.info("Loading page index...");
    File idxFile = new File(dir, FILE_PREFIX.concat(INDEX_SUFFIX));
    this.indexFile = new RandomAccessFile(idxFile, "rw");
    this.indexFileChannel = indexFile.getChannel();
    this.enqueueIndex = indexFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, INDEX_SIZE);
    this.dequeueIndex = (MappedByteBuffer) enqueueIndex.duplicate();
    enqueueIndex.position(EN_NUM_OFFSET);
    this.enqueuePageNumber = enqueueIndex.getInt();
    enqueueIndex.position(EN_POS_OFFSET);
    this.enqueuePosition = enqueueIndex.getInt();
    enqueueIndex.position(EN_CNT_OFFSET);
    this.enqueueCount = enqueueIndex.getInt();
    dequeueIndex.position(DE_NUM_OFFSET);
    this.dequeuePageNumber = enqueueIndex.getInt();
    dequeueIndex.position(DE_POS_OFFSET);
    this.dequeuePosition = enqueueIndex.getInt();
    dequeueIndex.position(DE_CNT_OFFSET);
    this.dequeueCount = enqueueIndex.getInt();
    logger.info("Page index [{}] has successfully loaded.", idxFile.getPath());

    // load en/dequeue page file
    loadEnqueuePage(getPageFile(getPagePath(getEnqueuePageNumber())));
    loadDequeuePage(getPageFile(getPagePath(getDequeuePageNumber())));
}
项目:alfresco-repository    文件:IndexInfo.java   
private boolean checkVersion(FileChannel channel) throws IOException
{
    if (channel.size() > 0)
    {
        channel.position(0);
        ByteBuffer buffer;

        if (useNIOMemoryMapping)
        {
            MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, 8);
            mbb.load();
            buffer = mbb;
        }
        else
        {
            buffer = ByteBuffer.wrap(new byte[8]);
            channel.read(buffer);
            buffer.position(0);
        }

        buffer.position(0);
        long onDiskVersion = buffer.getLong();
        return (version == onDiskVersion);
    }
    return (version == 0);
}
项目:odoxSync    文件:FileOperations.java   
private void processRegions(File file, RegionProcessor regionProcessor, String randomAccessFileMode, FileChannel.MapMode mapMode) throws IOException {
    try (
            RandomAccessFile randomAccessFile = new RandomAccessFile(file.getAbsolutePath().toFile(), randomAccessFileMode);
            FileChannel channel = randomAccessFile.getChannel()

    ) {
        RegionCalculator.calculateForSize(file, file.getSize());


        for (Region region : file.getRegions().values()) {
            Hasher hasher = Hashing.sha256().newHasher();
            MappedByteBuffer mappedByteBuffer = channel.map(mapMode, region.getOffset(), region.getSize());

            int sum = regionProcessor.processRegion(region, hasher, mappedByteBuffer);

            region.setQuickDigest(sum);

            byte[] slowDigest = hasher.hash().asBytes();
            region.setSlowDigest(slowDigest);

            clientMessageHandler.submitClientRegionMessage(clientId, file, region.getOffset(), region.getSize(), sum, slowDigest);
        }
    }
}
项目:guava-mock    文件:FilesTest.java   
public void testMap() throws IOException {
  // Test data
  int size = 1024;
  byte[] bytes = newPreFilledByteArray(size);

  // Setup
  File file = createTempFile();
  Files.write(bytes, file);

  // Test
  MappedByteBuffer actual = Files.map(file);

  // Verify
  ByteBuffer expected = ByteBuffer.wrap(bytes);
  assertTrue("ByteBuffers should be equal.", expected.equals(actual));
}
项目:guava-mock    文件:FilesTest.java   
public void testMap_readWrite() throws IOException {
  // Test data
  int size = 1024;
  byte[] expectedBytes = new byte[size];
  byte[] bytes = newPreFilledByteArray(1024);

  // Setup
  File file = createTempFile();
  Files.write(bytes, file);

  Random random = new Random();
  random.nextBytes(expectedBytes);

  // Test
  MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE);
  map.put(expectedBytes);

  // Verify
  byte[] actualBytes = Files.toByteArray(file);
  assertTrue(Arrays.equals(expectedBytes, actualBytes));
}
项目:guava-mock    文件:FilesTest.java   
public void testMap_readWrite_creates() throws IOException {
  // Test data
  int size = 1024;
  byte[] expectedBytes = newPreFilledByteArray(1024);

  // Setup
  File file = createTempFile();
  boolean deleted = file.delete();
  assertTrue(deleted);
  assertFalse(file.exists());

  // Test
  MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE, size);
  map.put(expectedBytes);

  // Verify
  assertTrue(file.exists());
  assertTrue(file.isFile());
  assertEquals(size, file.length());
  byte[] actualBytes = Files.toByteArray(file);
  assertTrue(Arrays.equals(expectedBytes, actualBytes));
}
项目:AndroidUtilCode-master    文件:FileIOUtils.java   
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByMap(File file, final byte[] bytes, boolean append, boolean isForce) {
    if (bytes == null || !FileUtils.createOrExistsFile(file)) return false;
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
        mbb.put(bytes);
        if (isForce) mbb.force();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:AndroidUtilCode-master    文件:FileIOUtils.java   
/**
 * 读取文件到字节数组中
 *
 * @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);
    }
}
项目:AndroidUtilCode-master    文件:CacheUtils.java   
private static byte[] readFile2Bytes(File file) {
    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[] data = new byte[size];
        mbb.get(data, 0, size);
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:BBSSDK-for-Android    文件:FileIOUtils.java   
/**
 * 将字节数组写入文件
 *
 * @param file    文件
 * @param bytes   字节数组
 * @param append  是否追加在文件末
 * @param isForce 是否写入文件
 * @return {@code true}: 写入成功<br>{@code false}: 写入失败
 */
public static boolean writeFileFromBytesByMap(final File file, final byte[] bytes, final boolean append, final boolean isForce) {
    if (bytes == null || !createOrExistsFile(file)) {
        return false;
    }
    FileChannel fc = null;
    try {
        fc = new FileOutputStream(file, append).getChannel();
        MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, fc.size(), bytes.length);
        mbb.put(bytes);
        if (isForce) {
            mbb.force();
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:BBSSDK-for-Android    文件:FileIOUtils.java   
/**
 * 读取文件到字节数组中
 *
 * @param file 文件
 * @return 字符数组
 */
public static byte[] readFile2BytesByMap(final File file) {
    if (!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);
    }
}
项目:RLibrary    文件:CacheUtils.java   
private static byte[] readFile2Bytes(File file) {
    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[] data = new byte[size];
        mbb.get(data, 0, size);
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:LJFramework    文件:CacheUtils.java   
private static byte[] readFile2Bytes(final File file) {
    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[] data = new byte[size];
        mbb.get(data, 0, size);
        return data;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        CloseUtils.closeIO(fc);
    }
}
项目:financisto1-holo    文件:DatabaseExport.java   
public static void copy(File source, File dest) throws IOException {
     FileChannel in = null, out = null;
     try {          
          in = new FileInputStream(source).getChannel();
          out = new FileOutputStream(dest).getChannel();

          long size = in.size();
          MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

          out.write(buf);

     } finally {
          if (in != null)          in.close();
          if (out != null)     out.close();
     }
}
项目:OpenJSharp    文件:MappedReadBuffer.java   
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);
}
项目:openjdk-jdk10    文件:InvokeCleaner.java   
@DataProvider(name = "badBuffers")
static Object[][] createBadBuffers() throws Exception {
    FileChannel fc = FileChannel.open(bob);
    closeables.add(fc);
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 10);

    return new Object[][] {
            { ByteBuffer.allocate(0) },
            { ByteBuffer.allocate(10) },
            { ByteBuffer.allocate(10).duplicate() },
            { ByteBuffer.allocate(10).slice() },
            { ByteBuffer.allocateDirect(10).duplicate() },
            { ByteBuffer.allocateDirect(10).slice() },
            { ByteBuffer.allocateDirect(0).duplicate() },
            { ByteBuffer.allocateDirect(0).slice() },
            { mbb.duplicate() },
            { mbb.slice() }
    };
}
项目:memory    文件:AllocateDirectMap.java   
@SuppressWarnings("resource")
static final ResourceState mapper(final ResourceState state) throws Exception {
  final long fileOffset = state.getFileOffset();
  final long capacity = state.getCapacity();
  checkOffsetAndCapacity(fileOffset, capacity);

  final File file = state.getFile();

  if (isFileReadOnly(file)) {
    state.setResourceReadOnly(); //The file itself could be writable
  }

  final String mode = "rw"; //we can't map it unless we use rw mode
  final RandomAccessFile raf = new RandomAccessFile(file, mode);
  state.putRandomAccessFile(raf);
  final FileChannel fc = raf.getChannel();
  final long nativeBaseOffset = map(fc, fileOffset, capacity);
  state.putNativeBaseOffset(nativeBaseOffset);

  // length can be set more than the file.length
  raf.setLength(capacity);
  final MappedByteBuffer mbb = createDummyMbbInstance(nativeBaseOffset);
  state.putMappedByteBuffer(mbb);
  return state;
}
项目:CatchSpy    文件:Code.java   
public static String getFileMD5String(String path) {
    try {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        FileChannel ch = in.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(byteBuffer);
        return bufferToHex(messageDigest.digest());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:sstable-adaptor    文件:SyncUtil.java   
public static MappedByteBuffer force(MappedByteBuffer buf)
{
    Preconditions.checkNotNull(buf);
    if (SKIP_SYNC)
    {
        Object fd = null;
        try
        {
            if (mbbFDField != null)
            {
                fd = mbbFDField.get(buf);
            }
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
        //This is what MappedByteBuffer.force() throws if a you call force() on an umapped buffer
        if (mbbFDField != null && fd == null)
            throw new UnsupportedOperationException();
        return buf;
    }
    else
    {
        return buf.force();
    }
}
项目:openjdk-jdk10    文件:MapTest.java   
/**
 * Maps blah file with a random offset and checks to see if read
 * from the ByteBuffer gets the right line number
 */
private static void testRead() throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.setLength(4);

    for (int x=0; x<1000; x++) {
        try (FileInputStream fis = new FileInputStream(blah)) {
            FileChannel fc = fis.getChannel();

            long offset = generator.nextInt(10000);
            long expectedResult = offset / CHARS_PER_LINE;
            offset = expectedResult * CHARS_PER_LINE;

            MappedByteBuffer b = fc.map(MapMode.READ_ONLY,
                                        offset, 100);

            for (int i=0; i<4; i++) {
                byte aByte = b.get(i);
                sb.setCharAt(i, (char)aByte);
            }

            int result = Integer.parseInt(sb.toString());
            if (result != expectedResult) {
                err.println("I expected "+expectedResult);
                err.println("I got "+result);
                throw new Exception("Read test failed");
            }
        }
    }
}
项目:GitHub    文件:FileHelper.java   
/**
 * 还剩多少字节没有下载
 *
 * @param recordBuffer buffer
 * @return 剩余的字节
 */
private long getResidue(MappedByteBuffer recordBuffer) {
    long residue = 0;
    for (int j = 0; j < maxThreads; j++) {
        long startTemp = recordBuffer.getLong(j * EACH_RECORD_SIZE);
        long endTemp = recordBuffer.getLong(j * EACH_RECORD_SIZE + 8);
        long temp = endTemp - startTemp + 1;
        residue += temp;
    }
    return residue;
}
项目:L2jBrasil    文件:GeoPathFinding.java   
private void LoadPathNodeFile(byte rx,byte ry)
{
    String fname = "./data/pathnode/"+rx+"_"+ry+".pn";
    short regionoffset = getRegionOffset(rx,ry);
    _log.info("PathFinding Engine: - Loading: "+fname+" -> region offset: "+regionoffset+"X: "+rx+" Y: "+ry);
    File Pn = new File(fname);
    int node = 0,size, index = 0;
    try {
        // Create a read-only memory-mapped file
        FileChannel roChannel = new RandomAccessFile(Pn, "r").getChannel();
        size = (int)roChannel.size();
        MappedByteBuffer nodes;
        if (Config.FORCE_GEODATA) //Force O/S to Loads this buffer's content into physical memory.
            //it is not guarantee, because the underlying operating system may have paged out some of the buffer's data
            nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size).load();
        else
            nodes = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);

        // Indexing pathnode files, so we will know where each block starts
        IntBuffer indexs = IntBuffer.allocate(65536);

        while(node < 65536)
        {
            byte layer = nodes.get(index);
            indexs.put(node, index);
            node++;
            index += layer*10+1;
        }
        _pathNodesIndex.put(regionoffset, indexs);
        _pathNodes.put(regionoffset, nodes);
    } catch (Exception e)
    {
        e.printStackTrace();
        _log.warning("Failed to Load PathNode File: "+fname+"\n");
    }

}
项目:java-google-speech-api    文件:RecognizerChunked.java   
/**
 * Converts the file into a byte[].
 * @param infile The File you want to specify
 * @return a byte array
 * @throws IOException if something goes wrong reading the file.
 */
private byte[] mapFileIn(File infile) throws IOException{
    FileInputStream fis = new FileInputStream(infile);
    try{
        FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory
        int sz = (int)fc.size();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
        byte[] data2 = new byte[bb.remaining()];
        bb.get(data2);
        return data2;
    }
    finally{//Ensures resources are closed regardless of whether the action suceeded
        fis.close();
    }
}
项目:Breakpoint-http    文件:StorageServiceImpl.java   
@Override
public void uploadFileByMappedByteBuffer(MultipartFileParam param) throws IOException {
    String fileName = param.getName();
    String uploadDirPath = finalDirPath + param.getMd5();
    String tempFileName = fileName + "_tmp";
    File tmpDir = new File(uploadDirPath);
    File tmpFile = new File(uploadDirPath, tempFileName);
    if (!tmpDir.exists()) {
        tmpDir.mkdirs();
    }

    RandomAccessFile tempRaf = new RandomAccessFile(tmpFile, "rw");
    FileChannel fileChannel = tempRaf.getChannel();

    //写入该分片数据
    long offset = CHUNK_SIZE * param.getChunk();
    byte[] fileData = param.getFile().getBytes();
    MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, offset, fileData.length);
    mappedByteBuffer.put(fileData);
    // 释放
    FileMD5Util.freedMappedByteBuffer(mappedByteBuffer);
    fileChannel.close();

    boolean isOk = checkAndSetUploadProgress(param, uploadDirPath);
    if (isOk) {
        boolean flag = renameFile(tmpFile, fileName);
        System.out.println("upload complete !!" + flag + " name=" + fileName);
    }
}
项目:incubator-netbeans    文件:MatcherUtils.java   
/**
 * Unmap mapped buffer.
 */
public static void unmap(MappedByteBuffer buffer) {
    try {
        Method getCleanerMethod = buffer.getClass().getMethod(
                "cleaner");                                         //NOI18N
        getCleanerMethod.setAccessible(true);
        // sun.misc.Cleaner
        Object cleaner = getCleanerMethod.invoke(buffer);
        cleaner.getClass().getMethod("clean").invoke(cleaner);
    } catch (Exception e) {
    }
}
项目:incubator-netbeans    文件:FastMatcher.java   
/**
 * Unmap mapped buffer.
 */
private void unmap(MappedByteBuffer buffer) {
    try {
        Method getCleanerMethod = buffer.getClass().getMethod(
                "cleaner");                                         //NOI18N
        getCleanerMethod.setAccessible(true);
        // sun.misc.Cleaner
        Object cleaner = getCleanerMethod.invoke(buffer);
        cleaner.getClass().getMethod("clean").invoke(cleaner);
    } catch (Exception e) {
    }
}
项目:otus_java_2017_10    文件:Trace.java   
static void mmap_read() throws Exception {
    RandomAccessFile file = new RandomAccessFile("/dev/shm/cache", "rw");
    MappedByteBuffer in = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1024);
    byte[] arr = new byte[128];
    in.get(arr);
    System.out.println("mmap: " + new String(arr));
    file.close();
}
项目:AndiCar    文件:FileUtils.java   
/**
     * copy a file
     *
     * @param source source file
     * @param dest   destination file
     * @return null on success; error message on failure
     */
    private static String copyFile(Context ctx, File source, File dest) {

//        if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
        if (!FileUtils.isFileSystemAccessGranted(ctx)) {
            return mResources.getString(R.string.error_102);
        }

        FileChannel in;
        FileChannel out;
        try {
            FileInputStream fileInputStream = new FileInputStream(source);
            in = fileInputStream.getChannel();
            FileOutputStream fileOutputStream = new FileOutputStream(dest);
            out = fileOutputStream.getChannel();

            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

            out.write(buf);

            fileInputStream.close();
            fileOutputStream.close();
            in.close();
            out.close();
        }
        catch (IOException e) {
//            Toast toast = Toast.makeText(ctx, "Error: " + e.getMessage(), Toast.LENGTH_LONG);
//            toast.show();
            mLastException = e;
            mLastErrorMessage = e.getMessage();
            return e.getMessage();
        }
        return null;
    }
项目:OpenDiabetes    文件:RAFileNIO.java   
private boolean enlargeFile(long newFileLength) {

        try {
            long newBufferLength = newFileLength;

            if (!readOnly) {
                newBufferLength = largeBufferSize;
            }

            MapMode mapMode = readOnly ? FileChannel.MapMode.READ_ONLY
                                       : FileChannel.MapMode.READ_WRITE;

            if (!readOnly && file.length() < fileLength + newBufferLength) {
                file.seek(fileLength + newBufferLength - 1);
                file.writeByte(0);
            }

            MappedByteBuffer[] newBuffers =
                new MappedByteBuffer[buffers.length + 1];
            MappedByteBuffer newBuffer = channel.map(mapMode, fileLength,
                newBufferLength);

            System.arraycopy(buffers, 0, newBuffers, 0, buffers.length);

            newBuffers[buffers.length] = newBuffer;
            buffers                    = newBuffers;
            fileLength                 += newBufferLength;

            logger.logDetailEvent("NIO buffer instance, file size "
                                  + fileLength);
        } catch (Throwable e) {
            logger.logDetailEvent("NOI buffer allocate failed, file size "
                                  + newFileLength);

            return false;
        }

        return true;
    }
项目:CryptoKnight    文件:FileEncrypt.java   
public static void wipeFile(String file2wipe) throws IOException, FileNotFoundException
{
    File f2w = new File(file2wipe);

     if (f2w.exists())
     {

        SecureRandom sr = new SecureRandom();
        RandomAccessFile raf = new RandomAccessFile(f2w, "rw");
        FileChannel channel = raf.getChannel();
        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());

        while (buffer.hasRemaining())
        {
            buffer.put((byte) 0);
        }
        buffer.force();
        buffer.rewind();

        while (buffer.hasRemaining())
        {
            buffer.put((byte) 0xFF);
        }
        buffer.force();
        buffer.rewind();

        byte[] data = new byte[1];
        while (buffer.hasRemaining())
        {
            sr.nextBytes(data);
            buffer.put(data[0]);
        }
        buffer.force();
        raf.close();
        f2w.delete(); 
     }
}