Java 在Mapr FS中写入字符串内容时附加的垃圾字符

Java 在Mapr FS中写入字符串内容时附加的垃圾字符,java,hadoop,file-io,bit-shift,mapr,Java,Hadoop,File Io,Bit Shift,Mapr,我们正在尝试实现REST-API,其中接收json响应并将其转换为字符串json格式。我们正试图通过打开流将此字符串内容写入Mapr FS FileSystem mfsHandler; ... ... fsDataStream = mfsHandler.create(new Path("/demo/test.txt"), true); String name = "Just to test"; byte[] namebytes = name.getBytes(); // fsDataStr

我们正在尝试实现REST-API,其中接收json响应并将其转换为字符串json格式。我们正试图通过打开流将此字符串内容写入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位右移?

这里的问题与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");
}
如果调用
getBytes()
,而不指定要使用的字符集,则将获得默认字符集。这一点在各地都可能有所不同,因此最好指定您想要的内容

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