简体   繁体   English

Base64无法将字符串解码为字节数组

[英]Base64 Failed to Decode String to Byte Array

I tried to decode a string to byte array using Base64 . 我尝试使用Base64string解码为字节数组。 But it returned null . 但是它返回null Here is the code: 这是代码:

    LZW lzw = new LZW();
    String enkripEmbedFileString = Base64.encode(byteFile);
    List<Short> compressed = lzw.compress(enkripEmbedFileString);

    String kompress = "";
    Iterator<Short> compressIterator = compressed.iterator();
    while (compressIterator.hasNext()) {
        String sch = compressIterator.next().toString();
        int in = Integer.parseInt(sch);
        char ch = (char) in;
        kompress = kompress + ch;
    }

    byteFile = Base64.decode(kompress);

I call "byteFile" variable at the last row in a code below this code and it throw NullPointerException . 我在此代码下方的代码的最后一行调用“ byteFile”变量,并抛出NullPointerException I have check the "kompress" variable and it's not null. 我检查了“ kompress”变量,它不为空。 It contains a string . 它包含一个string

All you need to know is, with that code I compress a string with LZW which require String for parameter and returns List<Short> . 您需要知道的是,用该代码我用LZW压缩了一个字符串,该字符串需要String作为参数并返回List<Short> And, I convert the List<Short> to a String with a loop that you can see. 而且,我将List<Short>转换为带有您可以看到的循环的字符串。

The problem is, why Base64 failed to convert String to byte[] , after that String modified with LZW? 问题是,为什么用LZW修改了String之后,为什么Base64无法将String转换为byte[]

Whereas, if I decompress the String first and than return the decompressed String to be converted with Base64 to byte[], has no problem. 相比之下,如果我先解压缩String,然后将要用Base64转换的解压缩的String返回到byte [],则没有问题。 It works. 有用。 Here is the code which works: 这是有效的代码:

    //LZW Compress      
    LZW lzw = new LZW();
    String enkripEmbedFileString = Base64.encode(byteFile);
    List<Short> compressed = lzw.compress(enkripEmbedFileString);

    String kompress = "";
    Iterator<Short> compressIterator = compressed.iterator();
    while (compressIterator.hasNext()) {
        String sch = compressIterator.next().toString();
        int in = Integer.parseInt(sch);
        char ch = (char) in;
        kompress = kompress + ch;
    }

    //Decompress        
    List<Short> kompressback = back(kompress);
    String decompressed = decompress(kompressback);

    byteFile = Base64.decode(decompressed);

Please, give me an explanation. 请给我一个解释。 Where is my fault? 我的错在哪里

Base64 decode can be applied only to strings that contain Base64 encoded data. Base64 解码只能应用于包含Base64 编码数据的字符串。 Since you encode and then compress, the result is not Base64. 由于先编码然后压缩,所以结果不是Base64。 You proved it yourself when you saw that uncompressing the data first allowed you to then decode the Base64 string. 当您看到解压缩数据首先使您能够解码Base64字符串时,便证明了自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM