【发布时间】:2016-05-26 06:16:33
【问题描述】:
我尝试使用Base64 将string 解码为字节数组。但它返回了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 压缩字符串,该字符串需要字符串作为参数并返回 List<Short>。而且,我将List<Short> 转换为带有你可以看到的循环的字符串。
问题是,为什么用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);
请给我一个解释。我的错在哪里?
【问题讨论】:
-
您是否检查过(即打印出)输入到 Base64 解码器的字符串?它是有效的 Base64 吗?
-
您的意思是,Base64 只能将使用 Base64 编码的字符串解码为?
-
这是合乎逻辑的,是的。尝试将 Base64 decode 应用于不是先前 Base64 encode 输出的字符串会产生什么结果?那没有任何意义。
-
那么,我的代码当然会返回 null,因为 String 已经用 LZW 修改并且再次与 Base64 不兼容?
-
好的,非常感谢@Jim Garrison
标签: java string base64 byte lzw