Java Tutorial/File/CharBuffer

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

Buffer Equality

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] args) {
   CharBuffer cb1 = CharBuffer.allocate(5), cb2 = CharBuffer.allocate(5);
   cb1.put("B").put("u").put("f").put("f").put("A");
   cb2.put("B").put("u").put("f").put("f").put("B");
   cb1.rewind();
   cb2.rewind();
   System.out.println(cb1.limit(4).equals(cb2.limit(4)));
 }

} //</source>



true


Buffer slice

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer buffer = CharBuffer.allocate(8);
   buffer.position(3).limit(5);
   CharBuffer sliceBuffer = buffer.slice();
   println(buffer);
   println(sliceBuffer);
   char[] myBuffer = new char[100];
   CharBuffer cb = CharBuffer.wrap(myBuffer);
   cb.position(12).limit(21);
   CharBuffer sliced = cb.slice();
   println(cb);
   println(sliced);
 }
 private static void println(CharBuffer cb) {
   System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity="
       + cb.capacity() + ", arrayOffset=" + cb.arrayOffset());
 }

} /*

  • /</source>



pos=3, limit=5, capacity=8, arrayOffset=0
pos=0, limit=2, capacity=2, arrayOffset=3
pos=12, limit=21, capacity=100, arrayOffset=0
pos=0, limit=9, capacity=9, arrayOffset=12


CharBuffer warps a ByteBuffer

   <source lang="java">

import java.nio.ByteBuffer; import java.nio.CharBuffer; public class MainClass {

 public static void main(String argv[]) {
   ByteBuffer bb = ByteBuffer.allocate(100);
   bb.mark();
   bb.position(5);
   bb.reset();
   bb.mark().position(5).reset();
   char[] myBuffer = new char[100];
   CharBuffer cb = CharBuffer.wrap(myBuffer);
   cb.position(12).limit(21);
   CharBuffer sliced = cb.slice();
   System.out
       .println("Sliced: offset=" + sliced.arrayOffset() + ", capacity=" + sliced.capacity());
 }

} //</source>



Sliced: offset=12, capacity=9


Convert ByteBuffer to a CharBuffer

   <source lang="java">

import java.nio.ByteBuffer; import java.nio.CharBuffer; 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();
   CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
   System.out.println("Char Buffer");
   while (cb.hasRemaining())
     System.out.println(cb.position() + " -> " + cb.get());
 }

}</source>





Convert ByteBuffer to CharBuffer

   <source lang="java">

import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; /**

* Test asCharBuffer view.
*/

public class MainClass {

 public static void main(String[] argv) throws Exception {
   ByteBuffer byteBuffer = ByteBuffer.allocate(7).order(ByteOrder.BIG_ENDIAN);
   CharBuffer charBuffer = byteBuffer.asCharBuffer();
   byteBuffer.put(0, (byte) 0);
   byteBuffer.put(1, (byte) "H");
   byteBuffer.put(2, (byte) 0);
   byteBuffer.put(3, (byte) "i");
   byteBuffer.put(4, (byte) 0);
   byteBuffer.put(5, (byte) "!");
   byteBuffer.put(6, (byte) 0);
   println(byteBuffer);
   println(charBuffer);
   // now slice it differently
   byteBuffer.position(4);
   charBuffer = byteBuffer.asCharBuffer();
   println(byteBuffer);
   println(charBuffer);
 }
 // Print info about a buffer
 private static void println(Buffer buffer) {
   System.out.println("pos=" + buffer.position() + ", limit=" + buffer.limit() + ", capacity="
       + buffer.capacity() + ": "" + buffer.toString() + """);
 }

} /*

  • /</source>



pos=0, limit=7, capacity=7: "java.nio.HeapByteBuffer[pos=0 lim=7 cap=7]"
pos=0, limit=3, capacity=3: "Hi!"
pos=4, limit=7, capacity=7: "java.nio.HeapByteBuffer[pos=4 lim=7 cap=7]"
pos=0, limit=1, capacity=1: "!"


Create a CharBuffer and put in some string

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer cb = CharBuffer.allocate(100);
   cb.put("This is a test String");
   cb.flip();
   // This throws an IllegalArgumentException
   cb.put(cb);
   System.out.println(cb);
 }

}</source>





Fill String to CharBuffer

   <source lang="java">

import java.nio.CharBuffer; /**

* Buffer fill/drain example. This code uses the simplest means of filling and
* draining a buffer: one element at a time.
*/

public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer buffer = CharBuffer.allocate(100);
   String string = "asdf";
   for (int i = 0; i < string.length(); i++) {
     buffer.put(string.charAt(i));
   }
   buffer.flip();
   drainBuffer(buffer);
   buffer.clear();
 }
 private static void drainBuffer(CharBuffer buffer) {
   while (buffer.hasRemaining()) {
     System.out.print(buffer.get());
   }
   System.out.println("");
 }

}</source>





Flip a CharBuffer

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] argv) throws Exception {
   char[] chars = new char[60];
   CharBuffer cb = CharBuffer.wrap(chars, 12, 42);
   println(cb);
   cb.put("This is a test String");
   cb.flip();
   println(cb);
   cb.clear();
   cb.put("Foobar");
   println(cb);
   for (int i = 0; i < 20; i++) {
     System.out.println("[" + i + "] = " + chars[i]);
   }
 }
 private static void println(CharBuffer cb) {
   System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity="
       + cb.capacity() + ", arrayOffset=" + cb.arrayOffset());
 }

} /*

  • /</source>



pos=12, limit=54, capacity=60, arrayOffset=0
pos=0, limit=33, capacity=60, arrayOffset=0
pos=6, limit=60, capacity=60, arrayOffset=0
[0] = F
[1] = o
[2] = o
[3] = b
[4] = a
[5] = r
...


Get array out of CharBuffer

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer cb = CharBuffer.allocate(100);
   cb.put("This is a test String");
   cb.flip();
   System.out.println("hasArray() = " + cb.hasArray());
   char[] carray = cb.array();
   System.out.print("array=");
   for (int i = 0; i < carray.length; i++) {
     System.out.print(carray[i]);
   }
   System.out.println("");
   System.out.flush();
 }

} /**/</source>



hasArray() = true
array=This is a test String


Save and read text using FileChannel with CharBuffer

   <source lang="java">

import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class MainClass {

 public static void main(String[] args) throws Exception {
   FileChannel fc = new FileOutputStream("data2.txt").getChannel();
   ByteBuffer buff = ByteBuffer.allocate(24); // More than needed
   buff.asCharBuffer().put("Some text");
   fc.write(buff);
   fc.close();
   fc = new FileInputStream("data2.txt").getChannel();
   buff.clear();
   fc.read(buff);
   buff.flip();
   System.out.println(buff.asCharBuffer());
 }

} /* */</source>



Some text


Test buffer duplication

   <source lang="java">

import java.nio.CharBuffer; /**

* Test buffer duplication.
*/

public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer buffer = CharBuffer.wrap("01234567");
   buffer.position(3).limit(6).mark().position(5);
   CharBuffer dupeBuffer = buffer.duplicate();
   buffer.clear();
   println(buffer);
   println(dupeBuffer);
   dupeBuffer.reset();
   println(dupeBuffer);
   dupeBuffer.clear();
   println(dupeBuffer);
 }
 private static void println(CharBuffer cb) {
   System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity="
       + cb.capacity() + ": "" + cb + """);
 }

} /**/</source>



pos=0, limit=8, capacity=8: "01234567"
pos=5, limit=6, capacity=8: "5"
pos=3, limit=6, capacity=8: "345"
pos=0, limit=8, capacity=8: "01234567"


Test the effects of buffer flipping

   <source lang="java">

import java.nio.CharBuffer; /**

* Test the effects of buffer flipping.
* 
*/

public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer cb = CharBuffer.allocate(15);
   cb.put("Hello World");
   println(cb);
   cb.flip();
   println(cb);
   cb.flip();
   println(cb);
 }
 private static void println(CharBuffer cb) {
   System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ": "" + cb + """);
 }

}</source>





Use CharBuffer

   <source lang="java">

import java.nio.ByteBuffer; import java.nio.CharBuffer; public class MainClass {

 private static void symmetricScramble(CharBuffer buffer) {
   while (buffer.hasRemaining()) {
     buffer.mark();
     char c1 = buffer.get();
     char c2 = buffer.get();
     buffer.reset();
     buffer.put(c2).put(c1);
   }
 }
 public static void main(String[] args) {
   char[] data = "UsingBuffers".toCharArray();
   ByteBuffer bb = ByteBuffer.allocate(data.length * 2);
   CharBuffer cb = bb.asCharBuffer();
   cb.put(data);
   System.out.println(cb.rewind());
   symmetricScramble(cb);
   System.out.println(cb.rewind());
   symmetricScramble(cb);
   System.out.println(cb.rewind());
 }

} /*

  • /</source>



UsingBuffers
sUniBgfuefsr
UsingBuffers


Use while loop to read a CharBuffer

   <source lang="java">

import java.nio.ByteBuffer; import java.nio.CharBuffer; 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();
   CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();
   System.out.println("Char Buffer");
   while (cb.hasRemaining())
     System.out.println(cb.position() + " -> " + cb.get());
 }

}</source>





Wrap a char array to a CharBuffer

   <source lang="java">

import java.nio.CharBuffer; public class MainClass {

 public static void main(String[] argv) throws Exception {
   CharBuffer buffer = CharBuffer.allocate(8);
   buffer.position(3).limit(5);
   CharBuffer sliceBuffer = buffer.slice();
   println(buffer);
   println(sliceBuffer);
   char[] myBuffer = new char[100];
   CharBuffer cb = CharBuffer.wrap(myBuffer);
   cb.position(12).limit(21);
   CharBuffer sliced = cb.slice();
   println(cb);
   println(sliced);
 }
 private static void println(CharBuffer cb) {
   System.out.println("pos=" + cb.position() + ", limit=" + cb.limit() + ", capacity="
       + cb.capacity() + ", arrayOffset=" + cb.arrayOffset());
 }

} /*

  • /</source>



pos=3, limit=5, capacity=8, arrayOffset=0
pos=0, limit=2, capacity=2, arrayOffset=3
pos=12, limit=21, capacity=100, arrayOffset=0
pos=0, limit=9, capacity=9, arrayOffset=12