我们正在尝试实现REST-API,其中接收json响应并将其转换为字符串json格式。我们尝试通过打开stream将此字符串内容写入Mapr FS。
FileSystem mfsHandler;
...
...
fsDataStream = mfsHandler.create(new Path("/demo/test.txt"), true);
String name = "Just to test";
byte[] namebytes = name.getBytes();
// fsDataStream.write(namebytes);
BufferedOutputStream bos = new BufferedOutputStream(fsDataStream);
bos.write(namebytes);然而,在写入内容时,它追加了8位,使字符串向右移动了8位。输出结果是:只需测试
我试着遵循后http://stackoverflow.com/questions/19687576/unwanted-chars-written-from-java-rest-api-to-hadoopdfs-using-fsdataoutputstream,但不能得到解决方案。
如何避免这种垃圾字符?有什么替代方案可以避免8位右移吗?
发布于 2017-05-13 07:27:43
这里的问题与Java字符串的编码有关。您可以选择在调用getBytes时要使用的编码。
例如,下面是一个小程序,它打印出三种不同编码的字节:
public void testEncoding() throws UnsupportedEncodingException {
String s = "Sample text üø 漢字";
asHex(System.out, s, "UTF-8");
asHex(System.out, s, "UTF-16");
asHex(System.out, s, "SHIFT_JIS");
}
public void asHex(PrintStream out, String msg, String encoding) throws UnsupportedEncodingException {
byte[] buf = msg.getBytes(encoding);
System.out.printf("\n\n%s - %s\n", msg, encoding);
for (int i = 0; i < buf.length; i++) {
byte b = buf[i];
System.out.printf("%02x ", b & 0xff);
if (i % 16 == 15) {
System.out.printf("\n");
}
}
System.out.printf("\n");
}下面是输出:
Sample text üø 漢字 - UTF-8
53 61 6d 70 6c 65 20 74 65 78 74 20 c3 bc c3 b8
20 e6 bc a2 e5 ad 97
Sample text üø 漢字 - UTF-16
fe ff 00 53 00 61 00 6d 00 70 00 6c 00 65 00 20
00 74 00 65 00 78 00 74 00 20 00 fc 00 f8 00 20
6f 22 5b 57
Sample text üø 漢字 - SHIFT_JIS
53 61 6d 70 6c 65 20 74 65 78 74 20 3f 3f 20 8a
bf 8e 9a 如果在没有指定要使用的字符集的情况下调用getBytes(),那么您将获得默认字符集。这可能会在各地有所不同,因此指定您想要的内容几乎总是更好的。
https://stackoverflow.com/questions/43833184
复制相似问题