Convert a String to a byte array and then back to the original String

后端 未结 4 2132
一整个雨季
一整个雨季 2020-12-01 07:33

Is it possible to convert a string to byte array and then convert it back to the original string in Java or Android?

My objective is to send some strings to a microc

4条回答
  •  既然无缘
    2020-12-01 07:49

    import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

    public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

    public static byte[] read(InputStream is) throws Exception
    {
        String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;
    
        // must need a Byte buffer
    
        byte[] buf = new byte[1024 * 16]
    
        // we will use 16 kilobytes
    
        int len = 0;
    
        // we need a new input stream
    
        FileInputStream is = new FileInputStream(path);
    
        // use the buffer to update our "MessageDigest" instance
    
        while(true)
        {
            len = is.read(buf);
            if(len < 0) break;
            md.update(buf, 0, len);
        }
    
        // close the input stream
    
        is.close();
    
        // call the "digest" method for obtaining the final hash-result
    
        byte[] ret = md.digest();
    
        System.out.println("Length of Hash: " + ret.length);
    
        for(byte b : ret)
        {
            System.out.println(b + ", ");
        }
    
        String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
    
        String verification = Hex.encodeHexString(ret);
    
        System.out.println();
    
        System.out.println("===")
    
        System.out.println(verification);
    
        System.out.println("Equals? " + verification.equals(compare));
    
    }
    

    }

提交回复
热议问题