UTF-8解码/字节数组到文件

时间:2018-01-09 14:39:29

标签: java c# utf-8

我收到一个UTF-8编码的JSON String va REST Web服务,并且必须从数据创建一个文件。字符串用C#编码,如:

UTF8Encoding encoding = new UTF8Encoding();
//fill object data
byte[] bytes = encoding.GetBytes(object.Serialize());

然后我反序列化JSON对象并在java中解码我需要的数据:

requestData是JSON字符串

requestData = requestData.substring(requestData.indexOf("{")+1, requestData.lastIndexOf("}") - requestData.indexOf("{") -1).replace("\"","");
        for(String s : requestData.split(",")) {
            String[] pair = s.split(":");
            if(pair[0].equals("data")) {
                binaryData = pair[1].getBytes("UTF-8");
            }
        }
return binaryData;

binaryData应该是代表byte array文件的.docx。但是,当我将byte array写入file并下载时,下载的文件可以打开,但文件的文本就像byte array一样。

UEsDBBQABgAIAAAAIQCuDuWM4wEAANMIAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC0ls1u2zAQhO8F8g4Cr4FEJ4egKCzn0KbHJkBdtFeaXFlERVIg17H99l1KtuAkqqVW8cWATM3Mx+XPan6/M1XyDD5oZ3N2k81YAlY6pe06Zz+WX9OPLAkorBKVs5CzPQR2v7j6MF/uawgJqW3IWYlYf+I8yBKMCJmrwdJI4bwRSI9+zWshf4s18NvZ7I5LZxEsphg92GL

任何想法我做错了什么,最好的劝告。

修改 我使用

byte[]写入文件
FileUtils.writeByteArrayToFile(dataFile, file);

1 个答案:

答案 0 :(得分:0)

目前:

binaryData = pair[1].getBytes("UTF-8");

pair[1]似乎是Base64编码的,所以它应该在Java端进行解码。有几种方法可以解码Java中的Base64。您可以尝试将其替换为:

binaryData = Base64.getDecoder().decode(pair[1]);