e164. using a bytebuffer to store strings.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 24 行

TXT
24
字号
This example demonstrates how to use a ByteBuffer to store characters. For example, an application may want to store strings in a file to avoid the conversion to and from bytes. The example creates a character view on the ByteBuffer that provides methods for reading and writing strings. 
This example does not convert characters and bytes. For an example on how to convert characters to and from bytes, see e186 Converting Between Strings (Unicode) and Other Character Set Encodings. 

    // Obtain a ByteBuffer; see also e158 Creating a ByteBuffer
    ByteBuffer buf = ByteBuffer.allocate(100);
    
    // Create a character ByteBuffer
    CharBuffer cbuf = buf.asCharBuffer();
    
    // Write a string
    cbuf.put("a string");
    
    // Convert character ByteBuffer to a string.
    // Uses characters between current position and limit so flip it first
    cbuf.flip();
    String s = cbuf.toString();  // a string
    // Does not affect position
    
    // Get a substring
    int start = 2; // start is relative to cbuf's current position
    int end = 5;
    CharSequence sub = cbuf.subSequence(start, end); // str

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?