簡體   English   中英

Base64無法將字符串解碼為字節數組

[英]Base64 Failed to Decode String to Byte Array

我嘗試使用Base64string解碼為字節數組。 但是它返回null 這是代碼:

    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);

我在此代碼下方的代碼的最后一行調用“ byteFile”變量,並拋出NullPointerException 我檢查了“ kompress”變量,它不為空。 它包含一個string

您需要知道的是,用該代碼我用LZW壓縮了一個字符串,該字符串需要String作為參數並返回List<Short> 而且,我將List<Short>轉換為帶有您可以看到的循環的字符串。

問題是,為什么用LZW修改了String之后,為什么Base64無法將String轉換為byte[]

相比之下,如果我先解壓縮String,然后將要用Base64轉換的解壓縮的String返回到byte [],則沒有問題。 有用。 這是有效的代碼:

    //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);

請給我一個解釋。 我的錯在哪里

Base64 解碼只能應用於包含Base64 編碼數據的字符串。 由於先編碼然后壓縮,所以結果不是Base64。 當您看到解壓縮數據首先使您能夠解碼Base64字符串時,便證明了自己。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM