How to convert Java String into byte[]?

后端 未结 8 1465
不知归路
不知归路 2020-11-22 16:00

Is there any way to convert Java String to a byte[] (not the boxed Byte[])?

In trying this:

System.ou         


        
相关标签:
8条回答
  • 2020-11-22 16:16

    Simply:

    String abc="abcdefghight";
    
    byte[] b = abc.getBytes();
    
    0 讨论(0)
  • 2020-11-22 16:18

    Try using String.getBytes(). It returns a byte[] representing string data. Example:

    String data = "sample data";
    byte[] byteData = data.getBytes();
    
    0 讨论(0)
  • 2020-11-22 16:20

    You might wanna try return new String(byteout.toByteArray(Charset.forName("UTF-8")))

    0 讨论(0)
  • 2020-11-22 16:23

    It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:

    Bool DmgrGetVersion (String szVersion);
    
    Char NewszVersion [200];
    Strcpy (NewszVersion, szVersion.t_str ());
    .t_str () applies to builder c ++ 2010
    
    0 讨论(0)
  • 2020-11-22 16:27

    The object your method decompressGZIP() needs is a byte[].

    So the basic, technical answer to the question you have asked is:

    byte[] b = string.getBytes();
    byte[] b = string.getBytes(Charset.forName("UTF-8"));
    byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only
    

    However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13, the [B means byte[] and 38ee9f13 is the memory address, separated by an @.

    For display purposes you can use:

    Arrays.toString(bytes);
    

    But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

    To get a readable String back from a byte[], use:

    String string = new String(byte[] bytes, Charset charset);
    

    The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String, depending upon the chosen charset.

    0 讨论(0)
  • 2020-11-22 16:29
      String example = "Convert Java String";
      byte[] bytes = example.getBytes();
    
    0 讨论(0)
提交回复
热议问题