2017-05-07 19 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()不指定字符集使用那麼你會得到什麼是你的默認字符集。這可能會在各地發生變化,因此指定您想要的內容幾乎總是更好。