Java NIO 字节缓冲区 : put and get strings

标签 java

我有以下测试代码。我想知道如何使用 Java NIO ByteBuffer 放置和获取字符串。 我在需要帮助的地方添加了两条评论。

package testPipe;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class TestMemBuff {

    static final String dataFile = "invoicedata";
    static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
    static final int[] units = { 12, 8, 13, 29, 50 };
    static final String[] descs = { "Java T-shirt", "Java Mug",
            "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

    public static Charset charset = Charset.forName("UTF-8");
    public static CharsetEncoder encoder = charset.newEncoder();
    public static CharsetDecoder decoder = charset.newDecoder();

    public static void main(String[] args) throws UnsupportedEncodingException {

        double price;
        int unit;
        String desc;
        double total = 0.0;

        ByteBuffer buf = ByteBuffer.allocate(1024);


        for (int i = 0; i < prices.length; i++) {
            buf.putDouble(prices[i]);
            buf.putInt(units[i]);
            buf.asCharBuffer().put(descs[i]);           // Is it correct?
        }

        buf.flip();

        // INPUT
        while (buf.hasRemaining()) {

            price = buf.getDouble();
            unit = buf.getInt();
            desc =  buf.asCharBuffer().toString();       //This must be wrong!
            System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                    unit, desc, price);
            total += unit * price;
        }
    }

}

这是我执行时的输出:

You ordered 12 units of ????
[...]

等等。

感谢您的关注

最佳答案

写作部分:

for (int i = 0; i < prices.length; i++) {
    buf.putDouble(prices[i]);
    buf.putInt(units[i]);

    byte[] descsBytes = descs[i].getBytes();
    buf.putInt(descsBytes.length);
    buf.put(descsBytes);
}

阅读部分:

while (buf.hasRemaining()) {

    price = buf.getDouble();
    unit = buf.getInt();

    int len = buf.getInt();
    byte[] bytes = new byte[len]; 
    buf.get(bytes);
    desc = new String(bytes);

    System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                unit, desc, price);
    total += unit * price;
}

关于Java NIO 字节缓冲区 : put and get strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24633980/

相关文章:

java - 与 JFXpanel 滚动条关联的事件

java - 如何获取应用程序退出前读取的数据库表的最后一行行号

java - C# `Interlocked.Exchange(Object, Object) : Object` 的 Java 等价物是什么?

java - box-java-sdk - 普通身份验证

java - 将 SIGINT 信号从 Java 发送到外部进程

java - 我试图通过获取和设置 x/y 值来使关键输入起作用,但它不起作用

java.lang.ClassNotFoundException : org. sqlite.JDBC

java - Maven 原型(prototype)插件未应用所有属性

java - 了解 Android 上的多点触控?

java - 以下代码如何工作