2017-05-07 20 views
0

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

回答

0

这里的问题与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()不指定字符集使用那么你会得到什么是你的默认字符集。这可能会在各地发生变化,因此指定您想要的内容几乎总是更好。