Java by API/java.nio/MappedByteBuffer — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 14:31, 31 мая 2010

MappedByteBuffer: force()

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, (int) channel.size());
    buf.put(0, (byte) 0xFF);
    buf.force();
    channel.close();
  }
}





MappedByteBuffer: getLong(int index)

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] args) throws Exception {
    File aFile = new File("C:/test.bin");
    RandomAccessFile ioFile = new RandomAccessFile(aFile, " rw");
    FileChannel ioChannel = ioFile.getChannel();
    final int PRIMESREQUIRED = 10;
    long[] primes = new long[PRIMESREQUIRED];
    int index = 0;
    final long REPLACEMENT = 999999L;
    final int PRIMECOUNT = (int) ioChannel.size() / 8;
    MappedByteBuffer buf = ioChannel.map(FileChannel.MapMode.READ_WRITE, 0L, ioChannel.size())
        .load();
    ioChannel.close();
    for (int i = 0; i < PRIMESREQUIRED; i++) {
      index = 8 * (int) (PRIMECOUNT * Math.random());
      primes[i] = buf.getLong(index);
      buf.putLong(index, REPLACEMENT);
    }
    for (long prime : primes) {
      System.out.printf("%12d", prime);
    }
    ioFile.close();
  }
}





MappedByteBuffer: putLong(int index, long value)

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] args) throws Exception {
    File aFile = new File("C:/test.bin");
    RandomAccessFile ioFile = new RandomAccessFile(aFile, " rw");
    FileChannel ioChannel = ioFile.getChannel();
    final int PRIMESREQUIRED = 10;
    long[] primes = new long[PRIMESREQUIRED];
    int index = 0;
    final long REPLACEMENT = 999999L;
    final int PRIMECOUNT = (int) ioChannel.size() / 8;
    MappedByteBuffer buf = ioChannel.map(FileChannel.MapMode.READ_WRITE, 0L, ioChannel.size())
        .load();
    ioChannel.close();
    for (int i = 0; i < PRIMESREQUIRED; i++) {
      index = 8 * (int) (PRIMECOUNT * Math.random());
      primes[i] = buf.getLong(index);
      buf.putLong(index, REPLACEMENT);
    }
    for (long prime : primes) {
      System.out.printf("%12d", prime);
    }
    ioFile.close();
  }
}