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

冷不防 2023-02-15 07:50 72阅读 0赞

在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!

标签: 字节数组 java 字符串

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

发表评论

表情:
评论列表 (有 0 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读