【问题标题】:how to store byte in an array and get back the string如何将字节存储在数组中并取回字符串
【发布时间】:2015-07-03 15:46:43
【问题描述】:

我必须在 java 中使用字节数组和字符串。我使用 java 读取文件并从 getBytes() 方法获取字节码,即 [B@1d1cdf7]

是否可以再次使用此代码。在我的程序中解码回 java字符串。 我需要字节数组,那么我如何将这个值存储在字节数组中。我想要某个东西 就像在另一个程序中一样,我没有原始文本,我只有字节 数组那么我怎样才能取回字符串结果。

【问题讨论】:

    标签: java string bytearray


    【解决方案1】:

    你可以这样使用:

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        while(/* condition */ ) { // Get bytes from the file
            // Append bytes to the byteArray
            stream.write(bytes); 
        }
    
        String str = new String(stream.toByteArray()); // Get the string representation
    

    【讨论】:

    • ankur 在我的文本文件文件中,我已将字节写入 [B@1d1cdf7] 。我的查询是如何将此值读取为字节数组
    • 使用 InputStream 类如 FileInputStream 将其读取为字节。
    • 你能举个例子吗
    • 请参考stackoverflow上的这篇文章。 stackoverflow.com/questions/858980/file-to-byte-in-java
    【解决方案2】:

    您需要将 getBytes() 转换为 String。

    public String toString(){
       return new String(getBytes());
    }
    

    【讨论】:

      【解决方案3】:

      要将字符串转换为字节数组试试这个

      String test = "This is a test";
      
      byte[] bytes = test.getBytes();
      System.out.println("Byte : " + bytes);
      

      现在将字节数组转换为字符串试试这个

      String s = new String(bytes);
      System.out.println("Text : " + s);
      

      输出

      Byte : [B@25154f
      
      Text : This is a test
      

      【讨论】:

      • downvoters 请告诉我这段代码有什么问题,以便我纠正它
      【解决方案4】:

      您可以使用 Base64 编码。这种编码方式更适合将二进制数据保存成字符串。

      Java 中的 Base64 api:

      sun.misc.BASE64Encoder;
      sun.misc.BASE64Decoder;
      

      【讨论】:

        猜你喜欢
        • 2013-07-04
        • 2022-07-20
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 1970-01-01
        相关资源
        最近更新 更多