当前位置:   article > 正文

如何在Java中将Byte []数组转换为String

java byte to string

在Java中,我们可以使用new String(bytes, StandardCharsets.UTF_8)将byte []转换为String。

JavaSample.java
  1. package com.mkyong.io;
  2. import java.nio.charset.StandardCharsets;
  3. public class JavaSample {
  4. public static void main(String[] args) {
  5. String example = "This is raw text!";
  6. byte[] bytes = example.getBytes();
  7. System.out.println("Text : " + example);
  8. System.out.println("Text [Byte Format] : " + bytes);
  9. // no, don't do this, it returns the address of the object in memory
  10. System.out.println("Text [Byte Format] : " + bytes.toString());
  11. // convert bytes[] to string
  12. String s = new String(bytes, StandardCharsets.UTF_8);
  13. System.out.println("Output : " + s);
  14. // UnsupportedEncodingException
  15. //String s = new String(bytes, "UTF_8");
  16. }
  17. }

输出量

  1. Text : This is raw text!
  2. Text [Byte Format] : [B@5ae9a829
  3. Text [Byte Format] : [B@5ae9a829
  4. Output : This is raw text!

翻译自: https://mkyong.com/java/how-do-convert-byte-array-to-string-in-java/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/数据挖掘灵魂/article/detail/61456
推荐阅读
相关标签
  

闽ICP备14008679号