Java/File Input Output/MappedByteBuffer

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

Map FileChannel to MappedByteBuffer

 
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String args[]) throws Exception {
    String filename = args[0];
    int start = 10;
    int length = 20;
    FileInputStream fin = new FileInputStream(filename);
    FileChannel finc = fin.getChannel();
    MappedByteBuffer mbb = finc.map(FileChannel.MapMode.READ_ONLY, start, length);
    for (int i = 0; i < length; ++i) {
      System.out.println(mbb.get(i);
    }
    fin.close();
  }
}





Persisting Changes to a Memory-Mapped ByteBuffer

 
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();
  }
}





Read file upside/down with RandomAccessFile

 
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
  public static void main(String[] args) throws Exception {
    RandomAccessFile f = new RandomAccessFile("hello.txt", "rw");
    FileChannel fc = f.getChannel();
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, f.length());
    int len = (int) f.length();
    for (int i = 0, j = len - 1; i < j; i++, j--) {
      byte b = mbb.get(i);
      mbb.put(i, mbb.get(j));
      mbb.put(j, b);
    }
    fc.close();
  }
}