代码之家  ›  专栏  ›  技术社区  ›  Bill the Lizard

如何将二进制数据转换为字符串并返回到Java中?

  •  27
  • Bill the Lizard  · 技术社区  · 16 年前

    我在一个文件中有二进制数据,我可以把它读入一个字节数组,然后毫无问题地进行处理。现在,我需要通过网络连接将部分数据作为XML文档中的元素发送。我的问题是,当我将数据从字节数组转换为字符串并返回到字节数组时,数据会损坏。我已经在一台机器上测试了这个问题,以隔离字符串转换的问题,所以我现在知道它不会被XML解析器或网络传输损坏。

    我现在得到的是

    byte[] buffer = ...; // read from file
    // a few lines that prove I can process the data successfully
    String element = new String(buffer);
    byte[] newBuffer = element.getBytes();
    // a few lines that try to process newBuffer and fail because it is not the same data anymore
    

    有人知道如何在不丢失数据的情况下将二进制转换为字符串并返回吗?

    答:谢谢山姆。我觉得自己像个白痴。昨天我得到了这个答案,因为我的SAX解析器在抱怨。出于某种原因,当我遇到这个看似独立的问题时,我没有想到这是同一问题的新症状。

    编辑:为了完整起见,我使用了 Base64 类从 Apache Commons Codec 打包解决此问题。

    4 回复  |  直到 11 年前
        1
  •  19
  •   Sam    16 年前

    如果用base64编码,这将把任何数据转换成ASCII安全文本,但是base64编码的数据比原始数据大。

        2
  •  35
  •   Afshin Moazami Darxis    11 年前

    String(byte[]) 将数据视为默认字符编码。因此,如何将字节从8位值转换为16位Java Unicode字符将不仅在操作系统之间发生变化,而且甚至可以在同一台机器上使用不同代码页的不同用户之间变化。此构造函数只适用于解码您自己的文本文件之一。不要尝试将任意字节转换为字符爪哇!

    编码为 base64 是一个很好的解决方案。这是通过SMTP(电子邮件)发送文件的方式。(免费)阿帕奇 Commons Codec 项目将完成这项工作。

    byte[] bytes = loadFile(file);          
    //all chars in encoded are guaranteed to be 7-bit ASCII
    byte[] encoded = Base64.encodeBase64(bytes);
    String printMe = new String(encoded, "US-ASCII");
    System.out.println(printMe);
    byte[] decoded = Base64.decodeBase64(encoded);
    

    或者,您可以使用Java 6。 DatatypeConverter :

    import java.io.*;
    import java.nio.channels.*;
    import javax.xml.bind.DatatypeConverter;
    
    public class EncodeDecode {    
      public static void main(String[] args) throws Exception {
        File file = new File("/bin/ls");
        byte[] bytes = loadFile(file, new ByteArrayOutputStream()).toByteArray();
        String encoded = DatatypeConverter.printBase64Binary(bytes);
        System.out.println(encoded);
        byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);
        // check
        for (int i = 0; i < bytes.length; i++) {
          assert bytes[i] == decoded[i];
        }
      }
    
      private static <T extends OutputStream> T loadFile(File file, T out)
                                                           throws IOException {
        FileChannel in = new FileInputStream(file).getChannel();
        try {
          assert in.size() == in.transferTo(0, in.size(), Channels.newChannel(out));
          return out;
        } finally {
          in.close();
        }
      }
    }
    
        3
  •  2
  •   Community pid    7 年前

    看到这个问题, How do you embed binary data in XML? 不要将byte[]转换为字符串,然后将其推送到XML中的某个地方,而是通过base64编码将byte[]转换为字符串(有些XML库有一个类型可以为您这样做)。一旦从XML中得到字符串,base64就会解码。

    使用 http://commons.apache.org/codec/

    由于各种奇怪的字符集限制和非priting字符的存在,您的数据可能会变得混乱。斗杆w/base64。

        4
  •  0
  •   Herms    16 年前

    如何构建XML文档?如果使用Java的内置XML类,则应该为您处理字符串编码。

    看看javax.xml和org.xml包。这就是我们用来生成XML文档的方法,它可以很好地处理所有的字符串编码和解码。

    ---编辑:

    嗯,我想我误解了这个问题。您不是要对一个常规字符串进行编码,而是要对一组任意的二进制数据进行编码?在这种情况下,在前面的注释中建议的base64编码可能是可行的方法。我认为这是用XML编码二进制数据的一种相当标准的方法。