Sat*_*rah 2 java string base64 byte lzw
我尝试使用解码一个string字节数组Base64.但它回来了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);
Run Code Online (Sandbox Code Playgroud)
我在这段代码下面的代码的最后一行调用"byteFile"变量,然后抛出NullPointerException.我检查了"kompress"变量,它不是null.它包含一个string.
您需要知道的是,使用该代码我使用LZW压缩字符串,该字符串需要参数字符串并返回List<Short>.并且,我将转换为List<Short>带有您可以看到的循环的String.
问题是,在用LZW修改String后,为什么Base64无法转换String为byte[]?
然而,如果我首先解压缩字符串而不是返回用Base64转换为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);
Run Code Online (Sandbox Code Playgroud)
请给我一个解释.我的错在哪里?
Base64 解码只能应用于包含Base64 编码数据的字符串.由于您编码然后压缩,结果不是Base64.当您看到解压缩数据时首先允许您解码Base64字符串时,您就自己证明了这一点.