首页 > 解决方案 > ByteBuffer 丢弃尾随的换行符

问题描述

这是我将字符串放入 ByteBuffer 的方法

String message="Hello\n\n";
ByteBuffer bresult = ByteBuffer.allocate(message.getBytes().length);
bresult.put(message.getBytes());
bresult.flip();

当我将 bytebuffer 转换为字符串以查看结果 \n\n 已从上述字符串中删除。这就是我将 ByteBuffer 转换为 String 的方式

print(new String(bresult.array()));

结果是 Hello 没有任何换行符。您可以从我的日志中看到以下屏幕截图中的结果 [![在此处输入图像描述][1]][1]

但是当我在像 message="Hello\n\n " 这样的 hello 字符串中添加空格时,结果如下: [![enter image description here][2]][2] 如您所见,hello 下面有一些换行符细绳。

标签: javaandroidstringbytebuffer

解决方案


我无法重现该问题。以下:

import java.nio.ByteBuffer;

public class App {

  public static void main(String[] args) {
    String str = "Hello\n\n";

    ByteBuffer buf = ByteBuffer.allocate(str.getBytes().length);
    buf.put(str.getBytes());
    buf.flip();

    String str2 = new String(buf.array());

    System.out.println(str.equals(str2));
    System.out.println(str2.endsWith("\n\n"));
  }
}

给出这个输出:

true
true

这意味着从String创建的byte[]字符与原始字符具有所有相同的字符String

一些注意事项:

  1. 上面的使用ByteBuffer是一种迂回的做法str2 = new String(str.getBytes())。我用过ByteBuffer,因为这就是你在问题中使用的。

  2. 小心String#getBytes()String#<init>(byte[])。两者都使用可能会或可能不会导致问题的默认平台编码。考虑明确指定编码。

  3. 如果我用我替换测试,System.out.print(str2)我得到以下输出:

    Hello
    
    

    那是“你好”,后跟两个换行符。如果println改为使用,则将有三个换行符。请注意,换行符通常不是直接可见的。


推荐阅读