java - 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 下面有一些换行符细绳。
解决方案
我无法重现该问题。以下:
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
。
一些注意事项:
上面的使用
ByteBuffer
是一种迂回的做法str2 = new String(str.getBytes())
。我用过ByteBuffer
,因为这就是你在问题中使用的。小心
String#getBytes()
和String#<init>(byte[])
。两者都使用可能会或可能不会导致问题的默认平台编码。考虑明确指定编码。如果我用我替换测试,
System.out.print(str2)
我得到以下输出:Hello
那是“你好”,后跟两个换行符。如果
println
改为使用,则将有三个换行符。请注意,换行符通常不是直接可见的。
推荐阅读
- oracle - javers 的 Oracle 存储库依赖项
- node.js - 如何在 Node.js 中获取现有服务器的实例?
- ssl - SSL 证书/模块错误 - pip 19.2.3 - Anaconda 提示
- python - 如何等待写入文本文件,逐行读取更改并打印?
- android-webview - Javascript注入出错
- python - 如何在python中将ndarray转换为整数
- python - 如何将用户输入保存到文本文件
- flutter - 颤振 - 以相反方向圆形边框
- javascript - 如何使用 axios 将文件上传到 Dropbox
- javascript - 使用 Knex,如何将连接表的相关行作为嵌套对象给出?