ByteBuffer 丢弃尾随的换行符
ByteBuffer discards trailing newline
下面是我如何将字符串放入 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]
但是当我向 hello 字符串添加空格时,例如 message="Hello\n\n " 结果如下:
[![在此处输入图片描述][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
这意味着从 byte[]
创建的 String
具有与原始 String
所有相同的字符。
一些注意事项:
上面ByteBuffer
的使用是做str2 = new String(str.getBytes())
的迂回方式。我使用 ByteBuffer
因为那是你在问题中使用的。
小心 String#getBytes()
和 String#<init>(byte[])
。两者都使用默认的平台编码,这可能会或可能不会导致问题。考虑明确指定编码。
如果我用 System.out.print(str2)
替换测试,我会得到以下输出:
Hello
这是“你好”后跟两个换行符。如果使用 println
代替,则会出现三个换行符。请注意,换行符通常不会直接显示。
下面是我如何将字符串放入 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]
但是当我向 hello 字符串添加空格时,例如 message="Hello\n\n " 结果如下: [![在此处输入图片描述][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
这意味着从 byte[]
创建的 String
具有与原始 String
所有相同的字符。
一些注意事项:
上面
ByteBuffer
的使用是做str2 = new String(str.getBytes())
的迂回方式。我使用ByteBuffer
因为那是你在问题中使用的。小心
String#getBytes()
和String#<init>(byte[])
。两者都使用默认的平台编码,这可能会或可能不会导致问题。考虑明确指定编码。如果我用
System.out.print(str2)
替换测试,我会得到以下输出:Hello
这是“你好”后跟两个换行符。如果使用
println
代替,则会出现三个换行符。请注意,换行符通常不会直接显示。