Java Tutorial/File/IntBuffer

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

Convert ByteBuffer to an IntBuffer

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class MainClass {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, "a" });
    bb.rewind();
    IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
    System.out.println("Int Buffer");
    while (ib.hasRemaining())
      System.out.println(ib.position() + " -> " + ib.get());
  }
}
/*
 */



Int Buffer
0 -> 0
1 -> 97


Manipulating ints in a ByteBuffer with an IntBuffer

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class MainClass {
  private static final int BSIZE = 1024;
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.allocate(BSIZE);
    IntBuffer ib = bb.asIntBuffer();
 
    ib.put(new int[] { 1, 2, 7, 9, 3, 8, 6 });
 
    System.out.println(ib.get(3));
    ib.put(3, 1811);
    ib.rewind();
    while (ib.hasRemaining()) {
      int i = ib.get();
      if (i == 0)
        break; // Else we"ll get the entire buffer
      System.out.println(i);
    }
  }
}
/*
*/



9
1
2
7
1811
3
8
6


Map FileChannel to an IntBuffer and read from the IntBuffer

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) throws IOException {
    FileChannel fc = new FileInputStream(new File("temp.tmp")).getChannel();
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).asIntBuffer();
    while (ib.hasRemaining())
      ib.get();
    fc.close();
  }
}





Put integers to a mapped IntBuffer

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) throws IOException {
    FileChannel fc = new RandomAccessFile(new File("temp.tmp"), "rw").getChannel();
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
    ib.put(0);
    for (int i = 1; i < 10; i++)
      ib.put(ib.get(i - 1));
    fc.close();
  }
}





Use while loop to read an IntBuffer

import java.nio.ByteBuffer;
import java.nio.IntBuffer;
public class MainClass {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, "a" });
    bb.rewind();
    IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();
    System.out.println("Int Buffer");
    while (ib.hasRemaining())
      System.out.println(ib.position() + " -> " + ib.get());
  }
}
/*
 */



Int Buffer
0 -> 0
1 -> 97