Java by API/java.nio/CharBuffer

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

CharBuffer: allocate(int capacity)

 
import java.nio.CharBuffer;
public class Main {
  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]);
    }
  }
}





CharBuffer: array()

 
import java.nio.CharBuffer;
public class Main {
  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]);
    }
  }
}





CharBuffer: arrayOffset()

  
import java.nio.CharBuffer;
public class Main {
  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());
  }
}





CharBuffer: capacity()

  
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class MainClass {
  public static void main(String[] args) {
    File aFile = new File("afile.txt");
    FileOutputStream outputFile = null;
    try {
      outputFile = new FileOutputStream(aFile, true);
      System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("\nByte buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", buf.position(), buf.limit(),
        buf.capacity());
    // Create a view buffer
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println("Char view buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", charBuf.position(), charBuf
        .limit(), charBuf.capacity());
    try {
      outputFile.close(); // Close the O/P stream & the channel
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}





CharBuffer: flip()

 

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





CharBuffer: get()

  
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Main {
  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());
  }
}





CharBuffer: hasArray()

 
import java.nio.CharBuffer;
public class Main {
  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]);
    }
  }
}





CharBuffer: hasRemaining()

 

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





CharBuffer: limit()

  
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class MainClass {
  public static void main(String[] args) {
    File aFile = new File("afile.txt");
    FileOutputStream outputFile = null;
    try {
      outputFile = new FileOutputStream(aFile, true);
      System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("\nByte buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", buf.position(), buf.limit(),
        buf.capacity());
    // Create a view buffer
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println("Char view buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", charBuf.position(), charBuf
        .limit(), charBuf.capacity());
    try {
      outputFile.close(); // Close the O/P stream & the channel
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}





CharBuffer: limit(int newLimit)

  
import java.nio.CharBuffer;
public class Main {
  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());
  }
}





CharBuffer: position()

  
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class MainClass {
  public static void main(String[] args) {
    File aFile = new File("afile.txt");
    FileOutputStream outputFile = null;
    try {
      outputFile = new FileOutputStream(aFile, true);
      System.out.println("File stream created successfully.");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    ByteBuffer buf = ByteBuffer.allocate(1024);
    System.out.println("\nByte buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", buf.position(), buf.limit(),
        buf.capacity());
    // Create a view buffer
    CharBuffer charBuf = buf.asCharBuffer();
    System.out.println("Char view buffer:");
    System.out.printf("position = %2d  Limit = %4d  capacity = %4d%n", charBuf.position(), charBuf
        .limit(), charBuf.capacity());
    try {
      outputFile.close(); // Close the O/P stream & the channel
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}





CharBuffer: put(char c)

  
import java.nio.CharBuffer;
public class Main {
  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)));
  }
}





CharBuffer: put(String str)

  
/*
 * Output:
 
 */
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) {
    try {
      File aFile = new File("test.txt");
      FileOutputStream outputFile = null;
      outputFile = new FileOutputStream(aFile, true);
      FileChannel outChannel = outputFile.getChannel();
      ByteBuffer buf = ByteBuffer.allocate(200);
      buf.putInt(10).asCharBuffer().put("www.jexp.ru");
      buf.position(10).flip();
      outChannel.write(buf);
      buf.clear();
      outputFile.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





CharBuffer: slice()

  
import java.nio.CharBuffer;
public class Main {
  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());
  }
}





CharBuffer: subSequence(int start, int end)

 
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer buf = ByteBuffer.allocate(100);
    CharBuffer cbuf = buf.asCharBuffer();
    cbuf.put("a string");
    int start = 2; // start is relative to cbuf"s current position
    int end = 5;
    CharSequence sub = cbuf.subSequence(start, end); // str
  }
}





CharBuffer: wrap(char[] array, int offset, int length)

 
import java.nio.CharBuffer;
public class Main {
  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());
  }
}





CharBuffer: wrap(CharSequence csq)

  
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class MainClass {
  public static void main(String[] args) throws Exception{
    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));
    for (;;) { // This server runs forever
      SocketChannel client = server.accept();
      String response = new java.util.Date().toString() + "\r\n";
      client.write(encoder.encode(CharBuffer.wrap(response)));
      client.close();
    }
  }
}